<?php

/**
 *   OPENSHOP 购物流程函数库
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: init.php,v 1.0 2009/06/12 07:35:58 modified $
 *   @author      FillBag <fillbag@hotmail.com>
 */

if (!defined('IN_OS')){
    die('Access Denied');
}

/**
 * 处理序列化的支付、配送的配置参数
 * 返回一个以name为索引的数组
 *
 * @access  public
 * @param   string       $cfg
 * @return  void
 */
function unserialize_config($cfg)
{
    if (is_string($cfg) && ($arr = unserialize($cfg)) !== false)
    {
        $config = array();

        foreach ($arr AS $key => $val)
        {
            $config[$val['name']] = $val['value'];
        }

        return $config;
    }
    else
    {
        return false;
    }
}
/**
 * 取得已安装的配送方式
 * @return  array   已安装的配送方式
 */
function shipping_list()
{
    $sql = 'SELECT shipping_id, shipping_name ' .
            'FROM ' . $GLOBALS['os']->table('shipping') .
            ' WHERE enabled = 1';

    return $GLOBALS['db']->getAll($sql);
}

/**
 * 取得配送方式信息
 * @param   int     $shipping_id    配送方式id
 * @return  array   配送方式信息
 */
function shipping_info($shipping_id)
{
    $sql = 'SELECT * FROM ' . $GLOBALS['os']->table('shipping') .
            " WHERE shipping_id = '$shipping_id' " .
            'AND enabled = 1';

    return $GLOBALS['db']->getRow($sql);
}

/**
 * 取得可用的配送方式列表
 * @param   array   $region_id_list     收货人地区id数组（包括国家、省、市、区）
 * @return  array   配送方式数组
 */
function available_shipping_list($region_id_list)
{
    $sql = 'SELECT s.shipping_id, s.shipping_code, s.shipping_name, ' .
                's.shipping_desc, s.insure, s.support_cod, a.configure ' .
            'FROM ' . $GLOBALS['os']->table('shipping') . ' AS s, ' .
                $GLOBALS['os']->table('shipping_area') . ' AS a, ' .
                $GLOBALS['os']->table('area_region') . ' AS r ' .
            'WHERE r.region_id ' . db_create_in($region_id_list) .
            ' AND r.shipping_area_id = a.shipping_area_id AND a.shipping_id = s.shipping_id AND s.enabled = 1';
            //var_dump($sql);die;
    return $GLOBALS['db']->getAll($sql);
}

/**
 * 取得某配送方式对应于某收货地址的区域信息
 * @param   int     $shipping_id        配送方式id
 * @param   array   $region_id_list     收货人地区id数组
 * @return  array   配送区域信息（config 对应着反序列化的 configure）
 */
function shipping_area_info($shipping_id, $region_id_list)
{
    $sql = 'SELECT s.shipping_code, s.shipping_name, ' .
                's.shipping_desc, s.insure, s.support_cod, a.configure ' .
            'FROM ' . $GLOBALS['os']->table('shipping') . ' AS s, ' .
                $GLOBALS['os']->table('shipping_area') . ' AS a, ' .
                $GLOBALS['os']->table('area_region') . ' AS r ' .
            "WHERE s.shipping_id = '$shipping_id' " .
            'AND r.region_id ' . db_create_in($region_id_list) .
            ' AND r.shipping_area_id = a.shipping_area_id AND a.shipping_id = s.shipping_id AND s.enabled = 1';
    $row = $GLOBALS['db']->getRow($sql);

    if (!empty($row))
    {
        $shipping_config = unserialize_config($row['configure']);
        if (isset($shipping_config['pay_fee']))
        {
            if (strpos($shipping_config['pay_fee'], '%') !== false)
            {
                $row['pay_fee'] = floatval($shipping_config['pay_fee']) . '%';
            }
            else
            {
                 $row['pay_fee'] = floatval($shipping_config['pay_fee']);
            }
        }
        else
        {
            $row['pay_fee'] = 0.00;
        }
    }

    return $row;
}

/**
 * 计算运费
 * @param   string  $shipping_code      配送方式代码
 * @param   mix     $shipping_config    配送方式配置信息
 * @param   float   $goods_weight       商品重量
 * @param   float   $goods_amount       商品金额
 * @param   float   $goods_number       商品数量
 * @return  float   运费
 */
function shipping_fee($shipping_code, $shipping_config, $goods_weight, $goods_amount, $goods_number='')
{
    if (!is_array($shipping_config))
    {
        $shipping_config = unserialize($shipping_config);
    }

    $filename = ROOT_PATH . 'includes/modules/shipping/' . $shipping_code . '.php';
    if (file_exists($filename))
    {
        include_once($filename);

        $obj = new $shipping_code($shipping_config);

        return $obj->calculate($goods_weight, $goods_amount, $goods_number);
    }
    else
    {
        return 0;
    }
}

/**
 * 获取指定配送的保价费用
 *
 * @access  public
 * @param   string      $shipping_code  配送方式的code
 * @param   float       $goods_amount   保价金额
 * @param   mix         $insure         保价比例
 * @return  float
 */
function shipping_insure_fee($shipping_code, $goods_amount, $insure)
{
    if (strpos($insure, '%') === false)
    {
        /* 如果保价费用不是百分比则直接返回该数值 */
        return floatval($insure);
    }
    else
    {
        $path = ROOT_PATH . 'includes/modules/shipping/' . $shipping_code . '.php';

        if (file_exists($path))
        {
            include_once($path);

            $shipping = new $shipping_code;
            $insure   = floatval($insure) / 100;

            if (method_exists($shipping, 'calculate_insure'))
            {
                return $shipping->calculate_insure($goods_amount, $insure);
            }
            else
            {
                return ceil($goods_amount * $insure);
            }
        }
        else
        {
            return false;
        }
    }
}

/**
 * 取得已安装的支付方式列表
 * @return  array   已安装的配送方式列表
 */
function payment_list()
{
    $sql = 'SELECT pay_id, pay_name ' .
            'FROM ' . $GLOBALS['os']->table('payment') .
            ' WHERE enabled = 1';

    return $GLOBALS['db']->getAll($sql);
}

/**
 * 取得支付方式信息
 * @param   int     $pay_id     支付方式id
 * @return  array   支付方式信息
 */
function payment_info($pay_id)
{
    $sql = 'SELECT * FROM ' . $GLOBALS['os']->table('payment') .
            " WHERE pay_id = '$pay_id' AND enabled = 1";
    return $GLOBALS['db']->getRow($sql);
}

/**
 * 获得订单需要支付的支付费用
 *
 * @access  public
 * @param   integer $payment_id
 * @param   float   $order_amount
 * @param   mix     $cod_fee
 * @return  float
 */
function pay_fee($payment_id, $order_amount, $cod_fee=null)
{
    $pay_fee = 0;
    $payment = payment_info($payment_id);
    $rate    = ($payment['is_cod'] && !is_null($cod_fee)) ? $cod_fee : $payment['pay_fee'];

    if (strpos($rate, '%') !== false)
    {
        /* 支付费用是一个比例 */
        $val     = floatval($rate) / 100;
        $pay_fee = $val > 0 ? $order_amount * $val /(1- $val) : 0;
    }
    else
    {
        $pay_fee = floatval($rate);
    }

    return round($pay_fee, 2);
}

/**
 * 取得可用的支付方式列表
 * @param   bool    $support_cod        配送方式是否支持货到付款
 * @param   int     $cod_fee            货到付款手续费（当配送方式支持货到付款时才传此参数）
 * @param   int     $is_online          是否支持在线支付
 * @return  array   配送方式数组
 */
function available_payment_list($support_cod, $cod_fee = 0, $is_online = false)
{
    $sql = 'SELECT pay_id, pay_code, pay_name, pay_fee, pay_desc, pay_config, is_cod' .
            ' FROM ' . $GLOBALS['os']->table('payment') .
            ' WHERE enabled = 1 ';
    if (!$support_cod)
    {
        $sql .= 'AND is_cod = 0 '; // 如果不支持货到付款
    }
    if ($is_online)
    {
        $sql .= "AND is_online = '1' ";
    }
    $sql .= 'ORDER BY pay_order'; // 排序
    $res = $GLOBALS['db']->query($sql);

    $list = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        if ($row['is_cod'] == '1')
        {
            $row['pay_fee'] = $cod_fee;
        }

        $row['format_pay_fee'] = strpos($row['pay_fee'], '%') !== false ? $row['pay_fee'] :
        price_format($row['pay_fee'], false);
        $list[] = $row;
    }

    //将财付通提升至第一个显示
    foreach ($list as $k =>$v)
    {
        if($v['pay_code'] == 'tenpay')
        {
            $tenpay = $list[$k];
            unset($list[$k]);
            array_unshift($list, $tenpay);
        }
    }

    return $list;
}

/**
 * 取得包装列表
 * @return  array   包装列表
 */
function pack_list()
{
    $sql = 'SELECT * FROM ' . $GLOBALS['os']->table('pack');
    $res = $GLOBALS['db']->query($sql);

    $list = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $row['format_pack_fee'] = price_format($row['pack_fee'], false);
        $row['format_free_money'] = price_format($row['free_money'], false);
        $list[] = $row;
    }

    return $list;
}

/**
 * 取得包装信息
 * @param   int     $pack_id    包装id
 * @return  array   包装信息
 */
function pack_info($pack_id)
{
    $sql = "SELECT * FROM " . $GLOBALS['os']->table('pack') .
            " WHERE pack_id = '$pack_id'";
    return $GLOBALS['db']->getRow($sql);
}

/**
 * 根据订单中的商品总额来获得包装的费用
 *
 * @access  public
 * @param   integer $pack_id
 * @param   float   $goods_amount
 * @return  float
 */
function pack_fee($pack_id, $goods_amount)
{
    $pack = pack_info($pack_id);

    $val = (floatval($pack['free_money']) <= $goods_amount && $pack['free_money'] > 0) ? 0 : floatval($pack['pack_fee']);

    return $val;
}

/**
 * 取得贺卡列表
 * @return  array   贺卡列表
 */
function card_list()
{
    $sql = "SELECT * FROM " . $GLOBALS['os']->table('card');
    $res = $GLOBALS['db']->query($sql);

    $list = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $row['format_card_fee'] = price_format($row['card_fee'], false);
        $row['format_free_money'] = price_format($row['free_money'], false);
        $list[] = $row;
    }

    return $list;
}

/**
 * 取得贺卡信息
 * @param   int     $card_id    贺卡id
 * @return  array   贺卡信息
 */
function card_info($card_id)
{
    $sql = "SELECT * FROM " . $GLOBALS['os']->table('card') .
            " WHERE card_id = '$card_id'";

    return $GLOBALS['db']->getRow($sql);
}

/**
 * 根据订单中商品总额获得需要支付的贺卡费用
 *
 * @access  public
 * @param   integer $card_id
 * @param   float   $goods_amount
 * @return  float
 */
function card_fee($card_id, $goods_amount)
{
    $card = card_info($card_id);

    return ($card['free_money'] <= $goods_amount && $card['free_money'] > 0) ? 0 : $card['card_fee'];
}

/**
 * 取得订单信息
 * @param   int     $order_id   订单id（如果order_id > 0 就按id查，否则按sn查）
 * @param   string  $order_sn   订单号
 * @return  array   订单信息（金额都有相应格式化的字段，前缀是formated_）
 */
function order_info($order_id, $order_sn = '')
{
    /* 计算订单各种费用之和的语句 */
    $total_fee = " (goods_amount - discount + tax + shipping_fee + insure_fee + pay_fee + pack_fee + card_fee) AS total_fee ";
    $order_id = intval($order_id);
    if ($order_id > 0)
    {
        $sql = "SELECT *, " . $total_fee . " FROM " . $GLOBALS['os']->table('order_info') .
                " WHERE order_id = '$order_id'";
    }
    else
    {
        $sql = "SELECT *, " . $total_fee . "  FROM " . $GLOBALS['os']->table('order_info') .
                " WHERE order_sn = '$order_sn'";
    }
    $order = $GLOBALS['db']->getRow($sql);
	$shipinfo = shipping_info($order['shipping_id']);

    /* 格式化金额字段 */
    if ($order)
    {
    	$order['order_sn2']   			  = substr($order['order_sn'],0,11);
    	$order['is_receive_print']   	  = $shipinfo['is_receive_print'];
        $order['formated_goods_amount']   = price_format($order['goods_amount'], false);
        $order['formated_discount']       = price_format($order['discount'], false);
        $order['formated_tax']            = price_format($order['tax'], false);
        $order['formated_shipping_fee']   = price_format($order['shipping_fee'], false);
        $order['formated_insure_fee']     = price_format($order['insure_fee'], false);
        $order['formated_pay_fee']        = price_format($order['pay_fee'], false);
        $order['formated_pack_fee']       = price_format($order['pack_fee'], false);
        $order['formated_card_fee']       = price_format($order['card_fee'], false);
        $order['formated_total_fee']      = price_format($order['total_fee'], false);
        $order['formated_money_paid']     = price_format($order['money_paid'], false);
        $order['formated_bonus']          = price_format($order['bonus'], false);
        $order['formated_integral_money'] = price_format($order['integral_money'], false);
        $order['formated_surplus']        = price_format($order['surplus'], false);
        $order['formated_order_amount']   = price_format(abs($order['order_amount']), false);
        $order['formated_add_time']       = local_date($GLOBALS['_CFG']['time_format'], $order['add_time']);
        $order['formated_prepay_time']    = local_date("Y-m-d H:i", $order['prepay_time']);
        if ($order['order_status'] == OS_RETURNED && $order['order_amount'] == '0.00')
        {
        	$order['order_status'] = OS_REFUSED;
        }
    }

    return $order;
}

/**
 * 取得退货（款）单信息
 * @param   int / string     $order_return_id   退货（款）单（先按id查，后按sn查）
 * @param   string  		 $order_return_sn   订单号
 * @return  array   		 					退货（款）单信息
 */
function order_return_info($order_return_id, $order_return_sn = '', $return_type = '1')
{
    $order_return_id = intval($order_return_id);
    if(intval($return_type))
    {
    	$return_type_str = " AND return_type='{$return_type}' ";
    }
    
    if ($order_return_id > 0)
    {
        $sql = "SELECT * FROM " . $GLOBALS['os']->table('order_return') .
                " WHERE id = '$order_return_id' $return_type_str ";
    }
    else
    {
        $sql = "SELECT * FROM " . $GLOBALS['os']->table('order_return') .
                " WHERE return_sn = '$order_return_sn' $return_type_str ";
    }
    $order_return = $GLOBALS['db']->getRow($sql);

    /* 格式化金额字段 */
    if ($order_return)
    {
        $order_return['add_time']       = local_date($GLOBALS['_CFG']['time_format'], $order['add_time']);
    }

    return $order_return;
}

/**
 * 判断订单是否已完成
 * @param   array   $order  订单信息
 * @return  bool
 */
function order_finished($order)
{
    return $order['order_status']  == OS_FINISH;
}

/**
 * 取得订单商品
 * @param   int     $order_id   订单id
 * @return  array   订单商品数组
 */
function order_goods($order_id)
{
	// 增加查询订单中商品是否被拒收
	
    $sql = "SELECT o.rec_id, o.goods_id, o.goods_name, o.goods_sn, o.market_price, o.goods_number, " .
    		"o.*,s.size_id,s.size_name,g.goods_thumb,".
            "o.goods_price, o.goods_attr, o.is_real, o.parent_id, o.is_gift, o.is_rejected, " .
            "o.goods_price * o.goods_number AS subtotal, o.extension_code,co.color_id,co.color_name,co.color_code,cl.img_file " .
            "FROM " . $GLOBALS['os']->table('order_goods') . " as o ".
    		"left join ".$GLOBALS['os']->table('goods') ." as g on g.goods_id = o.goods_id ".
            "left join ".$GLOBALS['os']->table('color') ." as co on o.color_id = co.color_id ".
			"left join ".$GLOBALS['os']->table('goods_color') ." as gc on o.color_id = gc.color_id and o.goods_id = gc.goods_id ".
			"left join ".$GLOBALS['os']->table('color_lib') ." as cl on gc.img_id = cl.img_id ".
			"left join ".$GLOBALS['os']->table('size') ." as s on o.size_id = s.size_id ".
            " WHERE order_id = '$order_id'";
            
    $res = $GLOBALS['db']->query($sql);

    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        if ($row['extension_code'] == 'package_buy')
        {
            $row['package_goods_list'] = get_package_goods($row['goods_id']);
        }
        
        $img_item = '<img src="'.$GLOBALS['_CFG']['pre_fetch_img'].$row['img_file'].'?40,40"  border="0" alt="'.$row['img_name'].'"/>';        
        
        $row['img_item'] = $img_item;
        
        $goods_list[] = $row;
    }

    //return $GLOBALS['db']->getAll($sql);
    return $goods_list;
}

/**
 * 取得订单总金额
 * @param   int     $order_id   订单id
 * @param   bool    $include_gift   是否包括赠品
 * @return  float   订单总金额
 */
function order_amount($order_id, $include_gift = true)
{
    $sql = "SELECT SUM(goods_price * goods_number) " .
            "FROM " . $GLOBALS['os']->table('order_goods') .
            " WHERE order_id = '$order_id'";
    if (!$include_gift)
    {
        $sql .= " AND is_gift = 0";
    }

    return floatval($GLOBALS['db']->getOne($sql));
}

/**
 * 取得某订单商品总重量和总金额（对应 cart_weight_price）
 * @param   int     $order_id   订单id
 * @return  array   ('weight' => **, 'amount' => **, 'formated_weight' => **)
 */
function order_weight_price($order_id)
{
    $sql = "SELECT SUM(g.goods_weight * o.goods_number) AS weight, " .
                "SUM(o.goods_price * o.goods_number) AS amount ," .
                "SUM(o.goods_number) AS number " .
            "FROM " . $GLOBALS['os']->table('order_goods') . " AS o, " .
                $GLOBALS['os']->table('goods') . " AS g " .
            "WHERE o.order_id = '$order_id' " .
            "AND o.goods_id = g.goods_id";

    $row = $GLOBALS['db']->getRow($sql);
    $row['weight'] = floatval($row['weight']);
    $row['amount'] = floatval($row['amount']);
    $row['number'] = intval($row['number']);

    /* 格式化重量 */
    $row['formated_weight'] = formated_weight($row['weight']);

    return $row;
}

/**
 * 获得订单中的费用信息
 *
 * @access  public
 * @param   array   $order
 * @param   array   $goods
 * @param   array   $consignee
 * @param   bool    $is_gb_deposit  是否团购保证金（如果是，应付款金额只计算商品总额和支付费用，可以获得的积分取 $gift_integral）
 * @return  array
 */
function order_fee($order, $goods, $consignee)
{
    /* 初始化订单的扩展code */
    if (!isset($order['extension_code']))
    {
        $order['extension_code'] = '';
    }

    if ($order['extension_code'] == 'group_buy')
    {
        $group_buy = group_buy_info($order['extension_id']);
    }

    $total  = array('real_goods_count' => 0,
                    'gift_amount'      => 0,
                    'goods_price'      => 0,
                    'market_price'     => 0,
                    'discount'         => 0,
                    'pack_fee'         => 0,
                    'card_fee'         => 0,
                    'shipping_fee'     => 0,
                    'shipping_insure'  => 0,
                    'integral_money'   => 0,
                    'bonus'            => 0,
                    'surplus'          => 0,
                    'cod_fee'          => 0,
                    'pay_fee'          => 0,
                    'tax'              => 0);
    $weight = 0;

    /* 商品总价 */
    foreach ($goods AS $val)
    {
        /* 统计实体商品的个数 */
        if ($val['is_real'])
        {
            $total['real_goods_count']++;
            
            $total['goods_price']  += $val['goods_price'] * $val['goods_number'];
            $total['market_price'] += $val['market_price'] * $val['goods_number'];
        }
        else
        {
        	$total['gift_amount'] += $val['goods_price'] * $val['goods_number'];
        	$total['gift_amount'] = abs($total['gift_amount']);
        } 	
    }

    $total['saving']    = $total['market_price'] - $total['goods_price'] + $total['gift_amount'];
    $total['save_rate'] = $total['market_price'] ? round($total['saving'] * 100 / $total['market_price']) . '%' : 0;
    $total['goods_price_formated']  = price_format($total['goods_price'], false);
    $total['market_price_formated'] = price_format($total['market_price'], false);
    $total['saving_formated']       = price_format($total['saving'], false);
  
//    $sql = "SELECT SUM(ABS(c.goods_price) * c.goods_number) " .
//            "FROM " . $GLOBALS['os']->table('cart') . " AS c, " . $GLOBALS['os']->table('favourable_activity') . " AS fa " .
//            "WHERE c.is_gift = fa.act_id " .
//            "AND c.session_id = '" . SESS_ID . "' " .
//            "AND c.rec_type = '" . CART_GENERAL_GOODS . "' " .
//            "AND c.is_gift > 0 AND (fa.act_type = " . FAT_PRICE . " OR fa.act_type = " . FAT_DISCOUNT . ")";   
//    $total['discount'] = $GLOBALS['db']->getOne($sql);       

    /* 折扣 */
    $discount = compute_discount();
    $total['discount'] = $discount['discount'];
    if ($total['discount'] > $total['goods_price'])
    {
        $total['discount'] = $total['goods_price'];
    }
    $total['discount_formated'] = price_format($total['discount'], false);

    /* 税额 */
    if (!empty($order['need_inv']) && $order['inv_type'] != '')
    {
        /* 查税率 */
        $rate = 0;
        foreach ($GLOBALS['_CFG']['invoice_type']['type'] as $key => $type)
        {
            if ($type == $order['inv_type'])
            {
                $rate = floatval($GLOBALS['_CFG']['invoice_type']['rate'][$key]) / 100;
                break;
            }
        }
        if ($rate > 0)
        {
            $total['tax'] = $rate * $total['goods_price'];
        }
    }
    $total['tax_formated'] = price_format($total['tax'], false);

    /* 包装费用 */
    if (!empty($order['pack_id']))
    {
        $total['pack_fee']      = pack_fee($order['pack_id'], $total['goods_price']);
    }
    $total['pack_fee_formated'] = price_format($total['pack_fee'], false);

    /* 贺卡费用 */
    if (!empty($order['card_id']))
    {
        $total['card_fee']      = card_fee($order['card_id'], $total['goods_price']);
    }
    $total['card_fee_formated'] = price_format($total['card_fee'], false);

    /* 红包 */
    if (!empty($order['bonus_id']))
    {
        $bonus          = bonus_info($order['bonus_id']);
        $total['bonus'] = $bonus['type_money'];
    }

    $total['bonus_formated'] = price_format($total['bonus'], false);
   
    /* 配送费用 */
    $shipping_cod_fee = NULL;

    if ($order['shipping_id'] > 0 && $total['real_goods_count'] > 0)
    {
        $region['country']  = $consignee['country'];
        $region['province'] = $consignee['province'];
        $region['city']     = $consignee['city'];
        $region['district'] = $consignee['district'];
        $shipping_info = shipping_area_info($order['shipping_id'], $region);

        if (!empty($shipping_info))
        {
            $weight_price = cart_weight_price();

            $total['shipping_fee'] = shipping_fee($shipping_info['shipping_code'],$shipping_info['configure'], $weight_price['weight'], $total['goods_price'], $weight_price['number']);

            if (!empty($order['need_insure']) && $shipping_info['insure'] > 0)
            {
                $total['shipping_insure'] = shipping_insure_fee($shipping_info['shipping_code'],
                    $total['goods_price'], $shipping_info['insure']);
            }
            else
            {
                $total['shipping_insure'] = 0;
            }

            if ($shipping_info['support_cod'])
            {
                $shipping_cod_fee = $shipping_info['pay_fee'];
            }
        }
    }

    $total['shipping_fee_formated']    = price_format($total['shipping_fee'], false);
    $total['shipping_insure_formated'] = price_format($total['shipping_insure'], false);

    // 购物车中的商品能享受红包支付的总额
    $bonus_amount = compute_discount_amount();
    // 红包和积分最多能支付的金额为商品总额
    $max_amount = $total['goods_price'] - $bonus_amount;
 
    /* 计算订单总额 */
    if ($order['extension_code'] == 'group_buy' && $group_buy['deposit'] > 0)
    {
        $total['amount'] = $total['goods_price'];
    }
    else
    {
//        $total['amount'] = $total['goods_price'] + $total['tax'] + $total['pack_fee'] + $total['card_fee'] +
            //$total['shipping_fee'] + $total['shipping_insure'] + $total['cod_fee'];
        $total['amount'] = $total['goods_price'] - $total['discount'] + $total['tax'] + $total['pack_fee'] + $total['card_fee'] +
            $total['shipping_fee'] + $total['shipping_insure'] + $total['cod_fee'];
        // 减去红包金额
        $use_bonus        = min($total['bonus'], $max_amount); // 实际减去的红包金额

        $total['bonus']   = $use_bonus;
        $total['bonus_formated'] = price_format($total['bonus'], false);
        $total['amount'] -= $use_bonus; // 还需要支付的订单金额
        $max_amount      -= $use_bonus; // 积分最多还能支付的金额
    }

    /* 余额 */
    $order['surplus'] = $order['surplus'] > 0 ? $order['surplus'] : 0;
    if ($total['amount'] > 0)
    {
        if (isset($order['surplus']) && $order['surplus'] > $total['amount'])
        {
            $order['surplus'] = $total['amount'];
            $total['amount']  = 0;
        }
        else
        {
            $total['amount'] -= floatval($order['surplus']);
        }
    }
    else
    {
        $order['surplus'] = 0;
        $total['amount']  = 0;
    }
    $total['surplus'] = $order['surplus'];
    $total['surplus_formated'] = price_format($order['surplus'], false);

    /* 积分 */
    $order['integral'] = $order['integral'] > 0 ? $order['integral'] : 0;
    if ($total['amount'] > 0 && $max_amount > 0 && $order['integral'] > 0)
    {
        $integral_money = value_of_integral($order['integral']);

        // 使用积分支付
        $use_integral            = min($total['amount'], $max_amount, $integral_money); // 实际使用积分支付的金额
        $total['amount']        -= $use_integral;
        $total['integral_money'] = $use_integral;
        $order['integral']       = integral_of_value($use_integral);
    }
    else
    {
        $total['integral_money'] = 0;
        $order['integral']       = 0;
    }
    $total['integral'] = $order['integral'];
    $total['integral_formated'] = price_format($total['integral_money'], false);

    /* 保存订单信息 */
    $_SESSION['flow_order'] = $order;

    /* 支付费用 */
    if (!empty($order['pay_id']) && ($total['real_goods_count'] > 0 || $_SESSION['flow_type'] != CART_EXCHANGE_GOODS))
    {
        $total['pay_fee']      = pay_fee($order['pay_id'], $total['amount'], $shipping_cod_fee);
    }

    $total['pay_fee_formated'] = price_format($total['pay_fee'], false);

    $total['amount']           += $total['pay_fee']; // 订单总额累加上支付费用
    $total['amount_formated']  = price_format($total['amount'], false);

    /* 取得可以得到的积分和红包 */
    if ($order['extension_code'] == 'group_buy')
    {
        $total['will_get_integral'] = $group_buy['gift_integral'];
    }
    else
    {
        $total['will_get_integral'] = get_give_integral($goods)-$total['discount'];
    }
    $total['will_get_bonus']        = price_format(get_total_bonus(), false);
    $total['formated_goods_price']  = price_format($total['goods_price'] - $total['gift_amount'], false);
    $total['formated_market_price'] = price_format($total['market_price'], false);
    $total['formated_saving']       = price_format($total['saving'], false);

    if ($order['extension_code'] == 'exchange_goods')
    {
        $sql = 'SELECT SUM(eg.exchange_integral) '.
               'FROM ' . $GLOBALS['os']->table('cart') . ' AS c,' . $GLOBALS['os']->table('exchange_goods') . 'AS eg '.
               "WHERE c.goods_id = eg.goods_id AND c.session_id= '" . SESS_ID . "' " .
               "  AND c.rec_type = '" . CART_EXCHANGE_GOODS . "' " .
               '  AND c.is_gift = 0 AND c.goods_id > 0 ' .
               'GROUP BY eg.goods_id';
        $exchange_integral = $GLOBALS['db']->getOne($sql);
        $total['exchange_integral'] = $exchange_integral;
    }

    return $total;
}

/**
 * 修改订单
 * @param   int     $order_id   订单id
 * @param   array   $order      key => value
 * @return  bool
 */
function update_order($order_id, $order)
{ 
	//die( print_r( $order ) );
    return $GLOBALS['db']->autoExecute($GLOBALS['os']->table('order_info'),
        $order, 'UPDATE', "order_id = '$order_id'");
}

function update_order_return($order_return_id, $order_return)
{
	return $GLOBALS['db']->autoExecute($GLOBALS['os']->table('order_return'),
        $order_return, 'UPDATE', "id = '$order_return_id'");
}

/**
 * 得到新订单号
 * @return  string
 */
function get_order_sn()
{
    /* 选择一个随机的方案 */
    mt_srand((double) microtime() * 1000000);
	
    $sn = substr(date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT),2);
	
    $code = $sn;
    $ncode = '0'.$code; 
    $even = 0; $odd = 0; 
    for ($x=0;$x<12;$x++) 
    { 
        if ($x % 2) { $odd += $ncode[$x]; } else { $even += $ncode[$x]; } 
    } 
    $code.=(10 - (($odd * 3 + $even) % 10)) % 10; 
    return $code;
}


function get_order_return_sn()
{
	/* 选择一个随机的方案 */
    mt_srand((double) microtime() * 1000000);
	
    $sn = substr(date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT),2);
	
    $code = $sn;
    $ncode = '0'.$code; 
    $even = 0; $odd = 0; 
    for ($x=0;$x<12;$x++) 
    { 
        if ($x % 2) { $odd += $ncode[$x]; } else { $even += $ncode[$x]; } 
    } 
    $code.=(10 - (($odd * 3 + $even) % 10)) % 10; 
    return 'THD'.$code;
}
/**
 * 取得购物车商品
 * @param   int     $type   类型：默认普通商品
 * @return  array   购物车商品数组
 */
function cart_goods($type = CART_GENERAL_GOODS)
{
            
    $sql = "select rec_id,user_id,session_id,c.goods_id, 
    		c.goods_sn,c.goods_name,c.market_price,c.goods_price,c.goods_number,c.goods_attr,c.is_real,c.extension_code,c.parent_id, 
			rec_type,c.is_gift,can_handsel,goods_attr_id,c.color_id, c.size_id, size_name, g.goods_thumb, 
			co.color_name,co.color_code,co.color_id,cl.img_file,cl.img_name,gc.img_id,c.goods_price * c.goods_number AS subtotal
			FROM  ".$GLOBALS['os']->table('cart') ." as c 
			LEFT join ".$GLOBALS['os']->table('goods') ." as g on g.goods_id = c.goods_id
			LEFT join ".$GLOBALS['os']->table('color') ." as co on c.color_id = co.color_id
			left join ".$GLOBALS['os']->table('goods_color') ." as gc on c.color_id = gc.color_id and c.goods_id = gc.goods_id 
			left join ".$GLOBALS['os']->table('color_lib') ." as cl on gc.img_id = cl.img_id 
			left join ".$GLOBALS['os']->table('size') ." as s on c.size_id = s.size_id ".
			" WHERE session_id = '" . SESS_ID . "' " .
			"AND rec_type = '$type'";
    $arr = $GLOBALS['db']->getAll($sql);
    /* 格式化价格 */
    foreach ($arr as $key => $value)
    {
        $arr[$key]['formated_market_price'] = price_format($value['market_price'], false);
        $arr[$key]['formated_goods_price']  = price_format($value['goods_price'], false);
        $arr[$key]['formated_subtotal']     = price_format($value['subtotal'], false);
        
        $img_item = '<img src="'.$GLOBALS['_CFG']['pre_fetch_img'].$value['img_file'].'" width="40" height="40" border="0" alt="'.$value['img_name'].'"/>';     
        //$img_item = $arr[$key]['img_file'];   
        
        $arr[$key]['img_url'] = $img_item;
        $arr[$key]['color_name'] = $arr[$key]['color_id']==0 ? '默认' : $arr[$key]['color_name'];
        $arr[$key]['size_name'] = $arr[$key]['size_id']==0 ? '默认' : $arr[$key]['size_name'];
    }

    return $arr;
}

/**
 * 取得购物车总金额
 * @params  boolean $include_gift   是否包括赠品
 * @param   int     $type           类型：默认普通商品
 * @return  float   购物车总金额
 */
function cart_amount($include_gift = true, $type = CART_GENERAL_GOODS)
{
    $sql = "SELECT SUM(goods_price * goods_number) " .
            " FROM " . $GLOBALS['os']->table('cart') .
            " WHERE session_id = '" . SESS_ID . "' " .
            "AND rec_type = '$type' ";

    if (!$include_gift)
    {
        $sql .= ' AND is_gift = 0 AND goods_id > 0';
    }

    return floatval($GLOBALS['db']->getOne($sql));
}

/**
 * 检查某商品是否已经存在于购物车
 *
 * @access  public
 * @param   integer     $id
 * @param   array       $spec
 * @param   int         $type   类型：默认普通商品
 * @return  boolean
 */
function cart_goods_exists($id, $spec, $type = CART_GENERAL_GOODS)
{
    /* 检查该商品是否已经存在在购物车中 */
    $sql = "SELECT COUNT(*) FROM " .$GLOBALS['os']->table('cart').
            "WHERE session_id = '" .SESS_ID. "' AND goods_id = '$id' ".
            "AND parent_id = 0 AND goods_attr = '" .get_goods_attr_info($spec). "' " .
            "AND rec_type = '$type'";

    return ($GLOBALS['db']->getOne($sql) > 0);
}

/**
 * 获得购物车中商品的总重量、总价格、总数量
 *
 * @access  public
 * @param   int     $type   类型：默认普通商品
 * @return  array
 */
function cart_weight_price($type = CART_GENERAL_GOODS)
{
    /* 获得购物车中商品的总重量 */
    $sql    = 'SELECT SUM(g.goods_weight * c.goods_number) AS weight, ' .
                    'SUM(c.goods_price * c.goods_number) AS amount, ' .
                    'SUM(c.goods_number) AS number '.
                'FROM ' . $GLOBALS['os']->table('cart') . ' AS c '.
                'LEFT JOIN ' . $GLOBALS['os']->table('goods') . ' AS g ON g.goods_id = c.goods_id '.
                "WHERE c.session_id = '" . SESS_ID . "' " .
                "AND rec_type = '$type'";
    $row = $GLOBALS['db']->getRow($sql);
    $row['weight'] = floatval($row['weight']);
    $row['amount'] = floatval($row['amount']);
    $row['number'] = intval($row['number']);
    /* 格式化重量 */
    $row['formated_weight'] = formated_weight($row['weight']);

    return $row;
}

/**
 * 添加商品到购物车
 *
 * @access  public
 * @param   integer $goods_id   商品编号
 * @param   integer $num        商品数量
 * @param   array   $spec       规格
 * @param   integer $parent     基本件
 * @return  boolean
 */
function addto_cart($goods_id, $num = 1, $color_id = 0, $size_id = 0 , $parent = 0)
{   
    $GLOBALS['err']->clean();

    /* 取得商品信息 */
    $sql = "SELECT g.goods_name, g.goods_sn, g.is_on_sale, g.is_real, ".
                "g.market_price, g.shop_price AS org_price, g.promote_price, g.promote_start_date, ".
                "g.promote_end_date, g.goods_weight, g.integral, g.extension_code, ".
                "g.goods_number, g.is_alone_sale, ".
                "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price ".
            " FROM " .$GLOBALS['os']->table('goods'). " AS g ".
            " LEFT JOIN " . $GLOBALS['os']->table('member_price') . " AS mp ".
                    "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ".
            " WHERE g.goods_id = '$goods_id'" .
            " AND g.is_delete = 0";
    $goods = $GLOBALS['db']->getRow($sql);

    if (empty($goods))  
    {   
        $str_msg = '对不起，指定的商品不存在';  
    	$GLOBALS['err']->add($str_msg, ERR_NOT_EXISTS);

        return false;
    }

    /* 如果是作为配件添加到购物车的，需要先检查购物车里面是否已经有基本件 */
    if ($parent > 0)
    {
        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('cart') .
                " WHERE goods_id='$parent' AND session_id='" . SESS_ID . "'";
        if ($GLOBALS['db']->getOne($sql) == 0)
        {
            $str_msg = '对不起，您希望将该商品做为配件购买，可是购物车中还没有该商品的基本件。'; 
        	$GLOBALS['err']->add($str_msg, ERR_NO_BASIC_GOODS);

            return false;
        }

        /* 检查该配件是否已经添加过了。 */
        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('cart') .
                " WHERE goods_id = '$goods_id' AND parent_id='$parent' AND session_id='" . SESS_ID . "'";

        if ($GLOBALS['db']->getOne($sql) > 0)
        { 
            $str_msg = '对不起，您的购物车中已经添加了该配件。';
        	$GLOBALS['err']->add($str_msg , ERR_NOT_EXISTS);

            return false;
        }
    }

    /* 是否正在销售 */
    if ($goods['is_on_sale'] == 0)
    { 
        $str_msg = '对不起，该商品已经下架。';
    	$GLOBALS['err']->add($str_msg, ERR_NOT_ON_SALE);

        return false;
    }

    /* 不是配件时检查是否允许单独销售 */
    if (empty($parent) && $goods['is_alone_sale'] == 0)
    { 
        $str_msg = '对不起，该商品不能单独销售。';
    	$GLOBALS['err']->add($str_msg, ERR_CANNT_ALONE_SALE);

        return false;
    }

    /* 检查库存 */
//    if ($GLOBALS['_CFG']['use_storage'] == 1 && $num > $goods['goods_number'])
//    {
//        $num = $goods['goods_number']; 
//        $str_msg = "对不起，该商品已经库存不足暂停销售。\n你现在要进行缺货登记来预订该商品吗？";
//        $GLOBALS['err']->add(sprintf($str_msg, $num), ERR_OUT_OF_STOCK);
//
//        return false;
//    }

    /* 计算商品的促销价格 */
    $spec_price             = spec_price($spec);
    $goods_price            = get_final_price($goods_id, $num, true, $spec);
    $goods['market_price'] += $spec_price;
    $goods_attr             = get_goods_attr_info($spec);
    //$goods_attr_id          = join(',', $spec);

    /* 初始化要插入购物车的基本件数据 */
    $parent = array(
        'user_id'       => $_SESSION['user_id'],
        'session_id'    => SESS_ID,
        'goods_id'      => $goods_id,
        'goods_sn'      => addslashes($goods['goods_sn']),
        'goods_name'    => addslashes($goods['goods_name']),
        'market_price'  => $goods['market_price'],
        'goods_attr'    => addslashes($goods_attr),
        'is_real'       => $goods['is_real'],
        'extension_code'=> $goods['extension_code'],
        'is_gift'       => 0,
        'rec_type'      => (!empty($_SESSION['agent_status']) && $_SESSION['agent_status'] == 2) ? CART_AGENT_GOODS : CART_GENERAL_GOODS,
    	'color_id'      => $color_id,
    	'size_id'       => $size_id
    );

    /* 取得该商品的基本件和该商品作为其配件的价格（条件是价格低） */
    $basic_list = array();
    $sql = "SELECT parent_id, goods_price " .
            "FROM " . $GLOBALS['os']->table('group_goods') .
            " WHERE goods_id = '$goods_id'" .
            " AND goods_price < '$goods_price'" .
            " ORDER BY goods_price";
    $res = $GLOBALS['db']->query($sql);
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $basic_list[$row['parent_id']] = $row['goods_price'];
    }

    /* 取得购物车中该商品每个基本件的数量 */
    $basic_count_list = array();
    if ($basic_list)
    {
        $sql = "SELECT goods_id, SUM(goods_number) AS count " .
                "FROM " . $GLOBALS['os']->table('cart') .
                " WHERE session_id = '" . SESS_ID . "'" .
                " AND parent_id = 0" .
                " AND goods_id " . db_create_in(array_keys($basic_list)) .
                " GROUP BY goods_id";
        $res = $GLOBALS['db']->query($sql);
        while ($row = $GLOBALS['db']->fetchRow($res))
        {
            $basic_count_list[$row['goods_id']] = $row['count'];
        }
    }

    /* 取得购物车中该商品每个基本件已有该商品配件数量，计算出每个基本件还能有几个该商品配件 */
    if ($basic_count_list)
    {
        $sql = "SELECT parent_id, SUM(goods_number) AS count " .
                "FROM " . $GLOBALS['os']->table('cart') .
                " WHERE session_id = '" . SESS_ID . "'" .
                " AND goods_id = '$goods_id'" .
                " AND parent_id " . db_create_in(array_keys($basic_count_list)) .
                " GROUP BY parent_id";
        $res = $GLOBALS['db']->query($sql);
        while ($row = $GLOBALS['db']->fetchRow($res))
        {
            $basic_count_list[$row['parent_id']] -= $row['count'];
        }
    }

    /* 循环插入配件 */
    foreach ($basic_list as $parent_id => $fitting_price)
    {
        /* 如果已全部插入，退出 */
        if ($num <= 0)
        {
            break;
        }

        /* 如果该基本件不再购物车中，执行下一个 */
        if (!isset($basic_count_list[$parent_id]))
        {
            continue;
        }

        /* 如果该基本件的配件数量已满，执行下一个基本件 */
        if ($basic_count_list[$parent_id] <= 0)
        {
            continue;
        }

        /* 作为该基本件的配件插入 */
        $parent['goods_price']  = max($fitting_price, 0);
        $parent['goods_number'] = min($num, $basic_count_list[$parent_id]);
        $parent['parent_id']    = $parent_id;
        $GLOBALS['db']->autoExecute($GLOBALS['os']->table('cart'), $parent, 'INSERT');

        /* 改变数量 */
        $num -= $parent['goods_number'];
    }

    /* 如果数量不为0，作为基本件插入 */
    if ($num > 0)
    {
         /* 检查该商品是否已经存在在购物车中 */
        $sql = "SELECT goods_number FROM " .$GLOBALS['os']->table('cart').
                " WHERE session_id = '" .SESS_ID. "' AND goods_id = '$goods_id' ".
        		" AND color_id = '$color_id' " .
        		" AND size_id = '$size_id' " .
        		" AND parent_id = 0 " .
                " AND rec_type = 'CART_GENERAL_GOODS' ";

        $row = $GLOBALS['db']->getRow($sql);

        // 启用新的库存管理操作
        $inventory_number = ''; 
        $sql_inventory = "select i.goods_number_available from " . $GLOBALS['os']->table('goods_inventory') . " as i where i.goods_id = ".$goods_id." and i.color_id = ".$color_id." and i.size_id = ".$size_id;
        $inventory_result = $GLOBALS['db']->getRow($sql_inventory);        
        if ($inventory_result) {
        	$inventory_number = $inventory_result['goods_number_available'];
        }else{
        	$inventory_number = 0;
        }
        
        if($row) //如果购物车已经有此物品，则更新
        {
            $num += $row['goods_number'];
            if ($GLOBALS['_CFG']['use_storage'] == 0 || $num <= $inventory_number)
            {
                $goods_price = get_final_price($goods_id, $num, true);
                $sql = "UPDATE " . $GLOBALS['os']->table('cart') . " SET goods_number = '$num'" .
                       " , goods_price = '$goods_price'".
                       " WHERE session_id = '" .SESS_ID. "' AND goods_id = '$goods_id' ".
                       " AND parent_id = 0 " .
                	   " AND color_id = '$color_id' " .
        		       " AND size_id = '$size_id' " .
                       " AND rec_type = 'CART_GENERAL_GOODS'";
                $GLOBALS['db']->query($sql);
            }
            else
            {
                $str_msg = "对不起，该商品已经库存不足暂停销售。\n你现在要进行缺货登记来预订该商品吗？";
            	$GLOBALS['err']->add(sprintf($str_msg, $num), ERR_OUT_OF_STOCK); 
                return false;
            }
        }
        else //购物车没有此物品，则插入
        {
        	if ($num > $inventory_number) {
                $str_msg = "对不起，该商品已经库存不足暂停销售。\n你现在要进行缺货登记来预订该商品吗？";
            	$GLOBALS['err']->add(sprintf($str_msg, $num), ERR_OUT_OF_STOCK); 
                return false;        		
        	}else{
	            $goods_price = get_final_price($goods_id, $num, true);
    	        $parent['goods_price']  = max($goods_price, 0);
        	    $parent['goods_number'] = $num;
            	$parent['parent_id']    = 0;
            	
            	$GLOBALS['db']->autoExecute($GLOBALS['os']->table('cart'), $parent, 'INSERT');
        	}
        }
    }

    /* 把赠品删除 */
    $sql = "DELETE FROM " . $GLOBALS['os']->table('cart') . " WHERE session_id = '" . SESS_ID . "' AND is_gift <> 0";
    $GLOBALS['db']->query($sql);

    return true;
}

/**
 * 清空购物车
 * @param   int     $type   类型：默认普通商品
 */
function clear_cart($type = CART_GENERAL_GOODS)
{
    $sql = "DELETE FROM " . $GLOBALS['os']->table('cart') .
            " WHERE session_id = '" . SESS_ID . "' AND rec_type = '$type'";
    $GLOBALS['db']->query($sql);
}

/**
 * 获得指定的商品属性
 *
 * @access  public
 * @param   array   $arr
 * @return  string
 */
function get_goods_attr_info($arr)
{
    $attr   = '';

    if (!empty($arr))
    {
        $fmt = "%s:%s[%s] \n";

        $sql = "SELECT a.attr_name, ga.attr_value, ga.attr_price ".
                "FROM ".$GLOBALS['os']->table('goods_attr')." AS ga, ".
                    $GLOBALS['os']->table('attribute')." AS a ".
                "WHERE " .db_create_in($arr, 'ga.goods_attr_id')." AND a.attr_id = ga.attr_id";
        $res = $GLOBALS['db']->query($sql);

        while ($row = $GLOBALS['db']->fetchRow($res))
        {
            $attr_price = round(floatval($row['attr_price']), 2);
            $attr .= sprintf($fmt, $row['attr_name'], $row['attr_value'], $attr_price);
        }

        $attr = str_replace('[0]', '', $attr);
    }

    return $attr;
}

/**
 * 取得用户信息
 * @param   int     $user_id    用户id
 * @return  array   用户信息
 */
function user_info($user_id)
{
    $sql = "SELECT * FROM " . $GLOBALS['os']->table('users') .
            " WHERE user_id = '$user_id'";
    $user = $GLOBALS['db']->getRow($sql);

    unset($user['question']);
    unset($user['answer']);

    /* 格式化帐户余额 */
    if ($user)
    {
//        if ($user['user_money'] < 0)
//        {
//            $user['user_money'] = 0;
//        }
        $user['formated_user_money'] = price_format($user['user_money'], false);
        $user['formated_frozen_money'] = price_format($user['frozen_money'], false);
    }

    return $user;
}

/**
 * 修改用户
 * @param   int     $user_id   订单id
 * @param   array   $user      key => value
 * @return  bool
 */
function update_user($user_id, $user)
{
    return $GLOBALS['db']->autoExecute($GLOBALS['os']->table('users'),
        $user, 'UPDATE', "user_id = '$user_id'");
}

/**
 * 取得用户地址列表
 * @param   int     $user_id    用户id
 * @return  array
 */
function address_list($user_id)
{
    $sql = "SELECT * FROM " . $GLOBALS['os']->table('user_address') .
            " WHERE user_id = '$user_id'";

    return $GLOBALS['db']->getAll($sql);
}

/**
 * 取得用户地址信息
 * @param   int     $address_id     地址id
 * @return  array
 */
function address_info($address_id)
{
    $sql = "SELECT * FROM " . $GLOBALS['os']->table('user_address') .
            " WHERE address_id = '$address_id'";

    return $GLOBALS['db']->getRow($sql);
}

/**
 * 取得用户当前可用红包
 * @param   int     $user_id        用户id
 * @param   float   $goods_amount   订单商品金额
 * @return  array   红包数组
 */
function user_bonus($user_id, $goods_amount = 0)
{
    $day    = getdate();
    $today  = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);

    $sql = "SELECT t.type_id, t.type_name, t.type_money, b.bonus_id " .
            "FROM " . $GLOBALS['os']->table('bonus_type') . " AS t," .
                $GLOBALS['os']->table('user_bonus') . " AS b " .
            "WHERE t.type_id = b.bonus_type_id " .
            "AND t.use_start_date <= '$today' " .
            "AND t.use_end_date >= '$today' " .
            "AND t.min_goods_amount <= '$goods_amount' " .
            "AND b.user_id<>0 " .
            "AND b.user_id = '$user_id' " .
            "AND b.order_id = 0";
    return $GLOBALS['db']->getAll($sql);
}

/**
 * 取得红包信息
 * @param   int     $bonus_id   红包id
 * @param   string  $bonus_sn   红包序列号
 * @param   array   红包信息
 */
function bonus_info($bonus_id, $bonus_sn = '')
{
    $sql = "SELECT t.*, b.* " .
            "FROM " . $GLOBALS['os']->table('bonus_type') . " AS t," .
                $GLOBALS['os']->table('user_bonus') . " AS b " .
            "WHERE t.type_id = b.bonus_type_id ";
    if ($bonus_id > 0)
    {
        $sql .= "AND b.bonus_id = '$bonus_id'";
    }
    else
    {
        $sql .= "AND b.bonus_sn = '$bonus_sn'";
    }
    return $GLOBALS['db']->getRow($sql);
}

/**
 * 检查红包是否已使用
 * @param   int $bonus_id   红包id
 * @return  bool
 */
function bonus_used($bonus_id)
{
    $sql = "SELECT order_id FROM " . $GLOBALS['os']->table('user_bonus') .
            " WHERE bonus_id = '$bonus_id'";

    return  $GLOBALS['db']->getOne($sql) > 0;
}

/**
 * 设置红包为已使用
 * @param   int     $bonus_id   红包id
 * @param   int     $order_id   订单id
 * @return  bool
 */
function use_bonus($bonus_id, $order_id)
{
    $sql = "UPDATE " . $GLOBALS['os']->table('user_bonus') .
            " SET order_id = '$order_id', used_time = '" . gmtime() . "' " .
            "WHERE bonus_id = '$bonus_id' LIMIT 1";

    return  $GLOBALS['db']->query($sql);
}

/**
 * 设置红包为未使用
 * @param   int     $bonus_id   红包id
 * @param   int     $order_id   订单id
 * @return  bool
 */
function unuse_bonus($bonus_id)
{
    $sql = "UPDATE " . $GLOBALS['os']->table('user_bonus') .
            " SET order_id = 0, used_time = 0 " .
            "WHERE bonus_id = '$bonus_id' LIMIT 1";

    return  $GLOBALS['db']->query($sql);
}

/**
 * 计算积分的价值（能抵多少钱）
 * @param   int     $integral   积分
 * @return  float   积分价值
 */
function value_of_integral($integral)
{
    $scale = floatval($GLOBALS['_CFG']['integral_scale']);

    return $scale > 0 ? round(($integral / 100) * $scale, 2) : 0;
}

/**
 * 计算指定的金额需要多少积分
 *
 * @access  public
 * @param   integer $value  金额
 * @return  void
 */
function integral_of_value($value)
{
    $scale = floatval($GLOBALS['_CFG']['integral_scale']);

    return $scale > 0 ? round($value / $scale * 100) : 0;
}

/**
 * 订单退款
 * @param   string  $user_id        用户id
 * @param   int     $refund_type    退款方式 1 到帐户余额 2 到退款申请（先到余额，再申请提款） 3 不处理
 * @param   string  $refund_note    退款说明
 * @param   float   $refund_amount  退款金额（如果为0，取订单已付款金额）
 * @return  bool
 */
function order_refund($order_return, $refund_type, $refund_note, $refund_amount = 0)
{
    /* 检查参数 */
    $user_id = $order_return['user_id'];
    if ($user_id == 0 && $refund_type == 1)
    {
        sys_msg('因为是匿名客户,无法退还账户余额！');
    }

    $amount = $refund_amount > 0 ? $refund_amount : $order_return['money_paid'];
    if ($amount <= 0)
    {
        return true;
    }

    if (!in_array($refund_type, array(1, 2, 3)))
    {
        sys_msg('非法的输入参数');
    }

    /* 备注信息 */
    if ($refund_note)
    {
        $change_desc = $refund_note;
    }
    else
    {
        include_once(SOURCE_PATH . 'languages/' .$GLOBALS['_CFG']['lang']. '/admin/order.php');
        $change_desc = sprintf($GLOBALS['_LANG']['order_refund'], $order_return['order_sn']);
    }

    /* 处理退款 */
    if (1 == $refund_type)
    {
        log_account_change($user_id, $amount, 0, 0, 0, $change_desc);

        return true;
    }
    elseif (2 == $refund_type)
    {
        /* 如果非匿名，退回余额 */
        if ($user_id > 0)
        {
            log_account_change($user_id, $amount, 0, 0, 0, $change_desc);
        }

        /* user_account 表增加提款申请记录 */
        $account = array(
            'user_id'      => $user_id,
            'amount'       => (-1) * $amount,
            'add_time'     => gmtime(),
            'user_note'    => $refund_note,
            'process_type' => SURPLUS_RETURN,
            'admin_user'   => $_SESSION['admin_name'],
            'admin_note'   => sprintf($GLOBALS['_LANG']['order_refund'], $order_return['order_sn']),
            'is_paid'      => 0
        );
        $GLOBALS['db']->autoExecute($GLOBALS['os']->table('user_account'), $account, 'INSERT');

        return true;
    }
    else
    {
        return true;
    }
}

/**
 * 获得购物车中的商品
 *
 * @access  public
 * @return  array
 */
function get_cart_goods()
{
    /* 初始化 */
    $goods_list = array();
    $total = array(
        'goods_price'  => 0, // 本店售价合计（有格式）
        'market_price' => 0, // 市场售价合计（有格式）
        'saving'       => 0, // 节省金额（有格式）
        'save_rate'    => 0, // 节省百分比
        'goods_amount' => 0, // 本店售价合计（无格式）
    );

    /* 循环、统计 */
	$sql = " select rec_id,user_id,session_id,c.goods_id, goods_sn,goods_name,market_price,goods_price,goods_number,
			goods_attr,is_real,extension_code,parent_id, rec_type,is_gift,can_handsel,goods_attr_id,
			c.color_id, c.size_id, size_name, co.color_id, co.color_name, co.color_code, gc.img_id, cl.img_file,
			IF(parent_id, parent_id, c.goods_id) AS pid 
			FROM  ".$GLOBALS['os']->table('cart') ." as c LEFT join ".$GLOBALS['os']->table('color') ." as co on c.color_id = co.color_id
			left join ".$GLOBALS['os']->table('goods_color') ." as gc on c.color_id = gc.color_id and c.goods_id = gc.goods_id
			LEFT JOIN ".$GLOBALS['os']->table('color_lib') ." AS cl ON gc.img_id = cl.img_id 
			left join ".$GLOBALS['os']->table('size') ." as s on c.size_id = s.size_id ".
			" WHERE session_id = '" . SESS_ID . "' AND rec_type = '" . 
			((!empty($_SESSION['agent_status']) && $_SESSION['agent_status'] == 2) ? CART_AGENT_GOODS : CART_GENERAL_GOODS) . "'" .
			" ORDER BY pid, parent_id";
    $res = $GLOBALS['db']->query($sql);

    /* 用于统计购物车中实体商品和虚拟商品的个数 */
    $virtual_goods_count = 0;
    $real_goods_count    = 0;

    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $total['goods_price']  += $row['goods_price'] * $row['goods_number'];
        $total['market_price'] += $row['market_price'] * $row['goods_number'];

        $row['subtotal']     = price_format($row['goods_price'] * $row['goods_number'], false);
        $row['goods_price']  = price_format($row['goods_price'], false);
        $row['market_price'] = price_format($row['market_price'], false);

        /* 统计实体商品和虚拟商品的个数 */
        if ($row['is_real'])
        {
            $real_goods_count++;
        }
        else
        {
            $virtual_goods_count++;
        }

        /* 查询规格 */
//        if (trim($row['goods_attr']) != '')
//        {
//            $sql = "SELECT attr_value FROM " . $GLOBALS['os']->table('goods_attr') . " WHERE goods_attr_id " .
//            db_create_in($row['goods_attr']);
//            $attr_list = $GLOBALS['db']->getCol($sql);
//            foreach ($attr_list AS $attr)
//            {
//                $row['goods_name'] .= ' [' . $attr . '] ';
//            }
//        }
        /* 增加是否在购物车里显示商品图 */
        if (($GLOBALS['_CFG']['show_goods_in_cart'] == "2" || $GLOBALS['_CFG']['show_goods_in_cart'] == "3") && $row['extension_code'] != 'package_buy')
        {
            $goods_thumb = $GLOBALS['db']->getOne("SELECT `goods_thumb` FROM " . $GLOBALS['os']->table('goods') . " WHERE `goods_id`='{$row['goods_id']}'");
            $row['goods_thumb'] = get_image_path($row['goods_id'], $goods_thumb, true);
        }
        if ($row['extension_code'] == 'package_buy')
        {
            $row['package_goods_list'] = get_package_goods($row['goods_id']);
        }

        $img_item = '<img src="'.$GLOBALS['_CFG']['pre_fetch_img'].$row['img_file'].'" width="40" height="40" border="0" alt="'.$row['img_name'].'"/>';        

        $row['img_item'] = $img_item;
        $row['color_name'] = $row['color_id']==0 ? '默认' : $row['color_name'];
        $row['size_name'] = $row['size_id']==0 ? '默认' : $row['size_name'];
        $goods_list[] = $row;
    }
    $total['goods_amount'] = $total['goods_price'];
    $total['saving']       = price_format($total['market_price'] - $total['goods_price'], false);
    if ($total['market_price'] > 0)
    {
        $total['save_rate'] = $total['market_price'] ? round(($total['market_price'] - $total['goods_price']) *
        100 / $total['market_price']).'%' : 0;
    }
    $total['goods_price']  = price_format($total['goods_price'], false);
    $total['market_price'] = price_format($total['market_price'], false);
    $total['real_goods_count']    = $real_goods_count;
    $total['virtual_goods_count'] = $virtual_goods_count;

    return array('goods_list' => $goods_list, 'total' => $total);
}

/**
 * 取得收货人信息
 * @param   int     $user_id    用户编号
 * @return  array
 */
function get_consignee($user_id)
{
    if (isset($_SESSION['flow_consignee']))
    {
        /* 如果存在session，则直接返回session中的收货人信息 */

        return $_SESSION['flow_consignee'];
    }
    else
    {
        /* 如果不存在，则取得用户的默认收货人信息 */
        $arr = array();

        if ($user_id > 0)
        {
            /* 取默认地址 */
            $sql = "SELECT ua.*".
                    " FROM " . $GLOBALS['os']->table('user_address') . "AS ua, ".$GLOBALS['os']->table('users').' AS u '.
                    " WHERE u.user_id='$user_id' AND ua.address_id = u.address_id";

            $arr = $GLOBALS['db']->getRow($sql);
        }

        return $arr;
    }
}

/**
 * 查询购物车（订单id为0）或订单中是否有实体商品
 * @param   int     $order_id   订单id
 * @param   int     $flow_type  购物流程类型
 * @return  bool
 */
function exist_real_goods($order_id = 0, $flow_type = CART_GENERAL_GOODS)
{
    if ($order_id <= 0)
    {
        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('cart') .
                " WHERE session_id = '" . SESS_ID . "' AND is_real = 1 " .
                "AND rec_type = '$flow_type'";
    }
    else
    {
        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('order_goods') .
                " WHERE order_id = '$order_id' AND is_real = 1";
    }

    return $GLOBALS['db']->getOne($sql) > 0;
}

/**
 * 检查收货人信息是否完整
 * @param   array   $consignee  收货人信息
 * @param   int     $flow_type  购物流程类型
 * @return  bool    true 完整 false 不完整
 */
function check_consignee_info($consignee, $flow_type)
{
    if (exist_real_goods(0, $flow_type))
    {
        /* 如果存在实体商品 */
        $res = !empty($consignee['consignee']) &&
            !empty($consignee['country']) &&
            !empty($consignee['email']) &&
            !empty($consignee['tel']);

        if ($res)
        {
            if (empty($consignee['province']))
            {
                /* 没有设置省份，检查当前国家下面有没有设置省份 */
                $pro = get_regions(1, $consignee['country']);
                $res = empty($pro);
            }
            elseif (empty($consignee['city']))
            {
                /* 没有设置城市，检查当前省下面有没有城市 */
                $city = get_regions(2, $consignee['province']);
                $res = empty($city);
            }
            elseif (empty($consignee['district']))
            {
                $dist = get_regions(3, $consignee['city']);
                $res = empty($dist);
            }
        }

        return $res;
    }
    else
    {
        /* 如果不存在实体商品 */
        return !empty($consignee['consignee']) &&
            !empty($consignee['email']) &&
            !empty($consignee['tel']);
    }
}

/**
 * 获得上一次用户采用的支付和配送方式
 *
 * @access  public
 * @return  void
 */
function last_shipping_and_payment()
{
    $sql = "SELECT shipping_id, pay_id " .
            " FROM " . $GLOBALS['os']->table('order_info') .
            " WHERE user_id = '$_SESSION[user_id]' " .
            " ORDER BY order_id DESC LIMIT 1";
    $row = $GLOBALS['db']->getRow($sql);

    if (empty($row))
    {
        /* 如果获得是一个空数组，则返回默认值 */
        $row = array('shipping_id' => 0, 'pay_id' => 0);
    }

    return $row;
}

/**
 * 取得当前用户应该得到的红包总额
 */
function get_total_bonus()
{
    $day    = getdate();
    $today  = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);

    /* 按商品发的红包 */
    $sql = "SELECT SUM(c.goods_number * t.type_money)" .
            "FROM " . $GLOBALS['os']->table('cart') . " AS c, "
                    . $GLOBALS['os']->table('bonus_type') . " AS t, "
                    . $GLOBALS['os']->table('goods') . " AS g " .
            "WHERE c.session_id = '" . SESS_ID . "' " .
            "AND c.is_gift = 0 " .
            "AND c.goods_id = g.goods_id " .
            "AND g.bonus_type_id = t.type_id " .
            "AND t.send_type = '" . SEND_BY_GOODS . "' " .
            "AND t.send_start_date <= '$today' " .
            "AND t.send_end_date >= '$today' " .
            "AND c.rec_type = '" . CART_GENERAL_GOODS . "'";
    $goods_total = floatval($GLOBALS['db']->getOne($sql));

    /* 取得购物车中非赠品总金额 */
    $sql = "SELECT SUM(goods_price * goods_number) " .
            "FROM " . $GLOBALS['os']->table('cart') .
            " WHERE session_id = '" . SESS_ID . "' " .
            " AND is_gift = 0 " .
            " AND rec_type = '" . CART_GENERAL_GOODS . "'";
    $amount = floatval($GLOBALS['db']->getOne($sql));

    /* 按订单发的红包 */
    $sql = "SELECT FLOOR('$amount' / min_amount) * type_money " .
            "FROM " . $GLOBALS['os']->table('bonus_type') .
            " WHERE send_type = '" . SEND_BY_ORDER . "' " .
            " AND send_start_date <= '$today' " .
            "AND send_end_date >= '$today' " .
            "AND min_amount > 0 ";
    $order_total = floatval($GLOBALS['db']->getOne($sql));

    return $goods_total + $order_total;
}

/**
 * 处理红包（下订单时设为使用，取消（无效，退货）订单时设为未使用
 * @param   int     $bonus_id   红包编号
 * @param   int     $order_id   订单号
 * @param   int     $is_used    是否使用了
 */
function change_user_bonus($bonus_id, $order_id, $is_used = true)
{
    if ($is_used)
    {
        $sql = 'UPDATE ' . $GLOBALS['os']->table('user_bonus') . ' SET ' .
                'used_time = ' . gmtime() . ', ' .
                "order_id = '$order_id' " .
                "WHERE bonus_id = '$bonus_id'";
    }
    else
    {
        $sql = 'UPDATE ' . $GLOBALS['os']->table('user_bonus') . ' SET ' .
                'used_time = 0, ' .
                'order_id = 0 ' .
                "WHERE bonus_id = '$bonus_id'";
    }
    $GLOBALS['db']->query($sql);
}

/**
 * 获得订单信息
 *
 * @access  private
 * @return  array
 */
function flow_order_info()
{
    $order = isset($_SESSION['flow_order']) ? $_SESSION['flow_order'] : array();

    /* 初始化配送和支付方式 */
    if (!isset($order['shipping_id']) || !isset($order['pay_id']))
    {
        /* 如果还没有设置配送和支付 */
        if ($_SESSION['user_id'] > 0)
        {
            /* 用户已经登录了，则获得上次使用的配送和支付 */
            $arr = last_shipping_and_payment();

            if (!isset($order['shipping_id']))
            {
                $order['shipping_id'] = $arr['shipping_id'];
            }
            if (!isset($order['pay_id']))
            {
                $order['pay_id'] = $arr['pay_id'];
            }
        }
        else
        {
            if (!isset($order['shipping_id']))
            {
                $order['shipping_id'] = 0;
            }
            if (!isset($order['pay_id']))
            {
                $order['pay_id'] = 0;
            }
        }
    }

    if (!isset($order['pack_id']))
    {
        $order['pack_id'] = 0;  // 初始化包装
    }
    if (!isset($order['card_id']))
    {
        $order['card_id'] = 0;  // 初始化贺卡
    }
    if (!isset($order['bonus']))
    {
        $order['bonus'] = 0;    // 初始化红包
    }
    if (!isset($order['integral']))
    {
        $order['integral'] = 0; // 初始化积分
    }
    if (!isset($order['surplus']))
    {
        $order['surplus'] = 0;  // 初始化余额
    }

    /* 扩展信息 */
    if (isset($_SESSION['flow_type']) && intval($_SESSION['flow_type']) != CART_GENERAL_GOODS)
    {
        $order['extension_code'] = $_SESSION['extension_code'];
        $order['extension_id'] = $_SESSION['extension_id'];
    }

    return $order;
}

/**
 * 多订单合并（以第一个为主）
 * @param   array     订单sn数组 
 * @return  成功返回true，失败返回错误信息
 */
function merge_orders($order_sns=array())
{
	$result = array();
	if (count($order_sns) <= 1) {
		$result['code'] = -1;
		$result['message'] = '请至少勾选两张以上的订单进行合并。';
		return $result;
	} else {
		$success_ids = array();
		$success_sns = array();
		$error_sns = array();
		$main_order = array();
		$order = array();
		
		foreach ($order_sns as $key => $val) {
			$cur_order = order_info(0, $val);
			if ($key == 0) { //以第一张订单为主
				$main_order = $cur_order;
				if (($main_order['order_status'] != OS_UNCONFIRMED && $main_order['order_status'] != OS_CONFIRMED)
					|| ($main_order['pay_status'] != PS_UNPAYED && $main_order['pay_status'] != PS_PAYED)
					|| ($main_order['shipping_status'] != SS_UNSHIPPED)) { //检查主订单状态、支付状态、发货状态
					$result['code'] = -1;
					$result['message'] = '请确保第一张订单的状态为 已确认或未确认、已付款或未付款、未发货。';
					return $result;
				} else {
					if ($main_order['shipping_id'] > 0) { //主订单配送元素
						$weight_price = order_weight_price($main_order['order_id']);
						$main_order['shipping_weight'] = $weight_price['weight'];
						$main_order['shipping_amount'] = $weight_price['amount'];
						$main_order['shipping_number'] = $weight_price['number'];
						$region_id_list = array($main_order['country'], $main_order['province'], $main_order['city'], $main_order['district']);
						$shipping_area = shipping_area_info($main_order['shipping_id'], $region_id_list);
						$main_order['shipping_area_code'] = $shipping_area['shipping_code'];
						$main_order['shipping_area_configure'] = unserialize($shipping_area['configure']);
						$main_order['shipping_area_insure'] = $shipping_area['insure'];
						$main_order['shipping_area_pay_fee'] = $shipping_area['pay_fee'];
					}
					$order = $main_order;
					array_push($success_ids, $main_order['order_id']);
					array_push($success_sns, $val);
				}	
			} else { //合并其它订单
				if (!$cur_order) { //订单不存在
					array_push($error_sns, $val);
				} else {
				    if ($main_order['user_id'] != $cur_order['user_id']) { //订单用户是否相同
				        array_push($error_sns, $val);
				    } elseif ($main_order['consignee'] != $cur_order['consignee']) { //订单收货人是否相同
				        array_push($error_sns, $val);
				    } elseif ($main_order['process_status'] != $cur_order['process_status']) { //订单处理状态是否相同
				    	array_push($error_sns, $val);
				    } elseif ($main_order['lock_status'] != $cur_order['lock_status']) { //订单锁定状态是否相同
				    	array_push($error_sns, $val);
				    } elseif ($GLOBALS['_CFG']['use_ors'] && ($main_order['range_status'] != $cur_order['range_status'])) { //配货状态
				    	array_push($error_sns, $val);
				    } elseif ($main_order['question_status'] != $cur_order['question_status']) { //问题单状态
				    	array_push($error_sns, $val);
				    } elseif ($main_order['extension_code'] != '' || $cur_order['extension_code'] != 0) { //是否普通订单
				    	array_push($error_sns, $val);
				    } elseif (($cur_order['order_status'] != OS_UNCONFIRMED && $cur_order['order_status'] != OS_CONFIRMED)
				    	|| ($cur_order['pay_status'] != PS_UNPAYED && $cur_order['pay_status'] != PS_PAYED)
				    	|| ($cur_order['shipping_status'] != SS_UNSHIPPED)) { //检查从订单状态、支付状态、发货状态
				    	array_push($error_sns, $val);
				    } elseif (($main_order['order_status'] != $cur_order['order_status']) 
				    	|| ($main_order['pay_status'] != $cur_order['pay_status']) 
				    	|| ($main_order['shipping_status'] != $cur_order['shipping_status'])) { //检查主从订单、支付、发货状态是否相同
				    	array_push($error_sns, $val);
				    } else {
				    	/* 合并订单 */
					    $order['order_id']  = '';
					    $order['add_time']  = gmtime();
					    /* 合并商品总金额 */
				    	$order['goods_amount'] += $cur_order['goods_amount'];
				    	/* 合并折扣 */
				    	$order['discount'] += $cur_order['discount'];
				    	/* 合并配送元素 */
				    	$cur_weight_price = order_weight_price($cur_order['order_id']);
				    	$order['shipping_weight'] += $cur_weight_price['weight'];
				    	$order['shipping_amount'] += $cur_weight_price['amount'];
				    	$order['shipping_number'] += $cur_weight_price['number'];
				    	/* 合并积分、红包、余额、已付款金额 */
	    				$order['integral']      += $cur_order['integral'];
	    				$order['bonus']         += $cur_order['bonus'];
	    				$order['surplus']       += $cur_order['surplus'];
	    				$order['money_paid']    += $cur_order['money_paid'];
	    				array_push($success_ids, $cur_order['order_id']);
	    				array_push($success_sns, $val);
				    }
				}
			}
		}
		
		/* 检验勾选的订单是否能够合并 */
	    if (count($success_ids) <= 1) {
	    	$result['code'] = -1;
			$result['message'] = '订单合并失败，请确保至少有一张订单与主订单的 发货人、收货人、订单状态、支付状态、发货状态、锁定状态、处理状态、问题单状态等 保持一致。';
			return $result;
	    } else {
			/* 计算配送费用 */
		    if ($order['shipping_id'] > 0) {
		        $order['shipping_fee'] = shipping_fee($order['shipping_area_code'], $order['shipping_area_configure'], $order['shipping_weight'], $order['shipping_amount'], $order['shipping_number']);
		        if ($order['insure_fee'] > 0) { //如果保价了，重新计算保价费
		            $order['insure_fee'] = shipping_insure_fee($order['shipping_area_code'], $order['goods_amount'], $order['shipping_area_insure']);
		        }
		    }
		
		    /* 计算包装费用 */
		    if ($order['pack_id'] > 0) {
		        $pack = pack_info($order['pack_id']);
		        $order['pack_fee'] = $pack['free_money'] > $order['goods_amount'] ? $pack['pack_fee'] : 0;
		    }
		    
		    /* 计算贺卡费用 */
		    if ($order['card_id'] > 0) {
		        $card = card_info($order['card_id']);
		        $order['card_fee'] = $card['free_money'] > $order['goods_amount'] ? $card['card_fee'] : 0;
		    }
		
		    /* 计算积分金额 */
		    $order['integral_money'] = value_of_integral($order['integral']);
		    
		    /* 计算应付款金额（不包括支付费用） */
		    $order['order_amount'] = $order['goods_amount'] - $order['discount']
		                           + $order['shipping_fee']
		                           + $order['insure_fee']
		                           + $order['pack_fee']
		                           + $order['card_fee']
		                           - $order['bonus']
		                           - $order['integral_money']
		                           - $order['surplus']
		                           - $order['money_paid'];
		
		    /* 重新计算支付费 */
		    if ($order['pay_id'] > 0) {
		        //货到付款手续费
		        $cod_fee          = $shipping_area ? $order['shipping_area_pay_fee'] : 0;
		        $order['pay_fee'] = pay_fee($order['pay_id'], $order['order_amount'], $cod_fee);
		        // 应付款金额加上支付费
		        $order['order_amount'] += $order['pay_fee'];
		    }
		
		    /* 合并来源字段 */
		    $order['merge_from'] = implode(',', $success_ids);
		    
		    /*---------- 插入订单表 ----------*/
		    do
		    {
		        $order['order_sn'] = get_order_sn();
		        if ($GLOBALS['db']->autoExecute($GLOBALS['os']->table('order_info'), addslashes_deep($order), 'INSERT')) {
		            break;
		        } else {
		            if ($GLOBALS['db']->errno() != 1062) {
		                die($GLOBALS['db']->errorMsg());
		            }
		        }
		    }
		    while (true); // 防止订单号重复
		    /* 获得订单号 */
		    $order_id = $GLOBALS['db']->insert_id();
		
		    /* 插入订单商品并保留原有商品 */
		    $sql = "INSERT INTO " . $GLOBALS['os']->table('order_goods') . "( " .
		                "order_id, goods_id, goods_name, goods_sn, goods_number, market_price, ".
		                "goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, color_id, size_id, send_number, is_rejected, goods_barcode) " .
		            " SELECT '$order_id', goods_id, goods_name, goods_sn, goods_number, market_price, ".
		                "goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, color_id, size_id, send_number, is_rejected, goods_barcode " .
		            " FROM " . $GLOBALS['os']->table('order_goods') ." as g ".
		            " WHERE g.order_id " . db_create_in($success_ids);
		    $GLOBALS['db']->query($sql);
		    
		    /* 更新订单红包 */
	    	$sql = "UPDATE " . $GLOBALS['os']->table('user_bonus') .
	               " SET order_id = '$order_id' " .
	               "WHERE order_id " . db_create_in($success_ids);
	    	$GLOBALS['db']->query($sql);
	    	
		    include_once(ROOT_PATH . 'includes/lib_clips.php');
		    /* 插入支付日志 */
		    insert_pay_log($order_id, $order['order_amount'], PAY_ORDER);
		    $new_order_sn = $GLOBALS['db']->getOne("SELECT order_sn FROM " . $GLOBALS['os']->table('order_info') . " WHERE order_id='{$order_id}'");
		    
		    /* 更新原来多个订单的状态为已合并 */
		    $arr['order_status'] = OS_MERGED;
		    $action_note = "合并订单 " . implode(',', $success_sns) . " - 并生成新的订单 " . $new_order_sn;
		    foreach ($success_ids as $key => $val) {
		    	$current_orderinfo = order_info($val);
		    	update_order($current_orderinfo['order_id'], $arr);
		    	order_action($current_orderinfo['order_sn'], OS_MERGED, $current_orderinfo['shipping_status'], $current_orderinfo['pay_status'], $action_note);
		    }
		    
		    /* 记录新订单的操作日志 */
		    order_action($new_order_sn, $main_order['order_status'], SS_UNSHIPPED, $main_order['pay_status'], $action_note);
		    
		    /* 记录新订单的挂起、配货日志 */
		    if ($main_order['process_status'] == OPS_SUSPEND) {
		    	$GLOBALS['db']->query("INSERT INTO ".$os->table('order_suspend')." (relating_order_id, relating_order_sn, suspend_reason, from_user, add_time) VALUES ('".$order_id."', '".$new_order_sn."', '合并被挂起的订单','合并订单','$add_time')");
		    }
		    if ($GLOBALS['_CFG']['use_ors'] && ($main_order['range_status'] == ORS_ERROR || $main_order['range_status'] == ORS_OUT)) {
		    	$GLOBALS['db']->query("INSERT INTO ".$os->table('order_out')." (relating_order_id, relating_order_sn, out_reason, from_user, add_time) VALUES ('".$order_id."', '".$new_order_sn."', '合并配货未成功订单','合并订单','$add_time')");
		    }    
		    
		    /* 合并订单信息 */
		    if (count($success_sns) > 1) {
		    	$result['code'] = 0;
		    	if (empty($message)) { $message = "订单 " . implode(',', $success_sns) . " 合并成功。"; }
		    	else { $message .= "<br/>&nbsp;&nbsp;&nbsp;订单 " . implode(',', $success_sns) . " 合并成功。"; }
		    }
		    if (count($error_sns) >= 1) {
		    	$result['code'] = -1;
		    	if (empty($message)) { $message = "订单 " . implode(',', $error_sns) . " 合并失败。"; }
		    	else { $message .= "<br/>&nbsp;&nbsp;&nbsp;订单 " . implode(',', $error_sns) . " 合并失败。"; }
		    }
		    
		    /* 返回合并信息 */
		    if (!empty($message)) { $result['message'] = $message; }
		    
		    return $result;
	    }
	}
}

/**
 * 两订单合并（暂未使用）
 * @param   string  $main_order_sn     主订单号 
 * @param   string  $slave_order_sn    从订单号
 * @return  成功返回true，失败返回错误信息
 */
function merge_order($main_order_sn, $slave_order_sn)
{
    /* 订单号不能为空 */
    if (trim($main_order_sn) == '' || trim($slave_order_sn) == '')
    {
        return $GLOBALS['_LANG']['order_sn_not_null'];
    }

    /* 订单号不能相同 */
    if ($main_order_sn == $slave_order_sn)
    {
        return $GLOBALS['_LANG']['two_order_sn_same'];
    }

    /* 取得订单信息 */
    $main_order = order_info(0, $main_order_sn);
    $slave_order   = order_info(0, $slave_order_sn);
    
    /* 检查订单是否存在 */
    if (!$main_order)
    {
        return sprintf($GLOBALS['_LANG']['order_not_exist'], $main_order_sn);
    }
    elseif (!$slave_order)
    {
        return sprintf($GLOBALS['_LANG']['order_not_exist'], $slave_order_sn);
    }
    
    /* 检查订单用户是否相同 */
    if ($main_order['user_id'] != $slave_order['user_id'])
    {
        return $GLOBALS['_LANG']['order_user_not_same'];
    }

    /* 检查订单收货人是否相同 */
    if ($main_order['consignee'] != $slave_order['consignee'])
    {
        return $GLOBALS['_LANG']['order_consignee_not_same'];
    } 
    
    /* 检查订单处理状态是否一致 */
    if ($main_order['process_status'] != $slave_order['process_status'])
    {
        return $GLOBALS['_LANG']['process_status_not_same'];
    }
    
    /* 检查订单锁定状态是否一致 */
    if ($main_order['lock_status'] != $slave_order['lock_status'])
    {
        return $GLOBALS['_LANG']['lock_status_not_same'];
    }    

    /* 检查合并的订单是否为普通订单，非普通订单不允许合并 */
    if ($main_order['extension_code'] != '' || $slave_order['extension_code'] != 0)
    {
        return $GLOBALS['_LANG']['merge_invalid_order'];
    }

    /* 检查主订单状态是否是已确认或未确认、已付款或未付款、未发货 */
    if ($main_order['order_status'] != OS_UNCONFIRMED && $main_order['order_status'] != OS_CONFIRMED)
    {
        return sprintf($GLOBALS['_LANG']['os_not_unconfirmed_or_confirmed'], $main_order_sn);
    }
    elseif ($main_order['pay_status'] != PS_UNPAYED && $main_order['pay_status'] != PS_PAYED)
    {
        return sprintf($GLOBALS['_LANG']['ps_not_unpayed_or_payed'], $main_order_sn);
    }
    elseif ($main_order['shipping_status'] != SS_UNSHIPPED)
    {
        return sprintf($GLOBALS['_LANG']['ss_not_unshipped'], $main_order_sn);
    }

    /* 检查从订单状态是否是已确认或未确认、已付款或未付款、未发货 */
    if ($slave_order['order_status'] != OS_UNCONFIRMED && $slave_order['order_status'] != OS_CONFIRMED)
    {
        return sprintf($GLOBALS['_LANG']['os_not_unconfirmed_or_confirmed'], $slave_order_sn);
    }
    elseif ($slave_order['pay_status'] != PS_UNPAYED && $slave_order['pay_status'] != PS_PAYED)
    {
        return sprintf($GLOBALS['_LANG']['ps_not_unpayed_or_payed'], $slave_order_sn);
    }
    elseif ($slave_order['shipping_status'] != SS_UNSHIPPED)
    {
        return sprintf($GLOBALS['_LANG']['ss_not_unshipped'], $slave_order_sn);
    }

    /* 检查主从订单状态和支付状态是否一致 */
    if ($main_order['order_status'] != $slave_order['order_status'])
    {
        return $GLOBALS['_LANG']['os_status_not_same'];
    }
    elseif ($main_order['pay_status'] != $slave_order['pay_status'])
    {
        return $GLOBALS['_LANG']['ps_status_not_same'];
    }
        
    /* 合并订单 */
    $order = $main_order;
    $order['order_id']  = '';
    $order['add_time']  = gmtime();

    // 合并商品总额
	$order['goods_amount'] += $slave_order['goods_amount'];

    // 合并折扣
    $order['discount'] += $slave_order['discount'];

    if ($order['shipping_id'] > 0)
    {
        // 重新计算配送费用
        $weight_price       = order_weight_price($main_order['order_id']);
        $from_weight_price  = order_weight_price($slave_order['order_id']);
        $weight_price['weight'] += $from_weight_price['weight'];
        $weight_price['amount'] += $from_weight_price['amount'];
        $weight_price['number'] += $from_weight_price['number'];

        $region_id_list = array($order['country'], $order['province'], $order['city'], $order['district']);
        $shipping_area = shipping_area_info($order['shipping_id'], $region_id_list);

        $order['shipping_fee'] = shipping_fee($shipping_area['shipping_code'],
            unserialize($shipping_area['configure']), $weight_price['weight'], $weight_price['amount'], $weight_price['number']);

        // 如果保价了，重新计算保价费
        if ($order['insure_fee'] > 0)
        {
            $order['insure_fee'] = shipping_insure_fee($shipping_area['shipping_code'], $order['goods_amount'], $shipping_area['insure']);
        }
    }

    // 重新计算包装费、贺卡费
    if ($order['pack_id'] > 0)
    {
        $pack = pack_info($order['pack_id']);
        $order['pack_fee'] = $pack['free_money'] > $order['goods_amount'] ? $pack['pack_fee'] : 0;
    }
    if ($order['card_id'] > 0)
    {
        $card = card_info($order['card_id']);
        $order['card_fee'] = $card['free_money'] > $order['goods_amount'] ? $card['card_fee'] : 0;
    }

    // 合并积分、红包、余额、已付款金额
    $order['integral']      += $slave_order['integral'];
    $order['integral_money'] = value_of_integral($order['integral']);
    $order['surplus']       += $slave_order['surplus'];
    $order['bonus']         += $slave_order['bonus'];
    $order['money_paid']    += $slave_order['money_paid'];

    // 计算应付款金额（不包括支付费用）
    $order['order_amount'] = $order['goods_amount'] - $order['discount']
                           + $order['shipping_fee']
                           + $order['insure_fee']
                           + $order['pack_fee']
                           + $order['card_fee']
                           - $order['bonus']
                           - $order['integral_money']
                           - $order['surplus']
                           - $order['money_paid'];

    // 重新计算支付费
    if ($order['pay_id'] > 0)
    {
        // 货到付款手续费
        $cod_fee          = $shipping_area ? $shipping_area['pay_fee'] : 0;
        $order['pay_fee'] = pay_fee($order['pay_id'], $order['order_amount'], $cod_fee);

        // 应付款金额加上支付费
        $order['order_amount'] += $order['pay_fee'];
    }

    /* 插入订单表 */
    do
    {
        $order['order_sn'] = get_order_sn();
        if ($GLOBALS['db']->autoExecute($GLOBALS['os']->table('order_info'), addslashes_deep($order), 'INSERT'))
        {
            break;
        }
        else
        {
            if ($GLOBALS['db']->errno() != 1062)
            {
                die($GLOBALS['db']->errorMsg());
            }
        }
    }
    while (true); // 防止订单号重复

    /* 订单号 */
    $order_id = $GLOBALS['db']->insert_id();

    /* 更新订单商品 */
    //$sql = 'UPDATE ' . $GLOBALS['os']->table('order_goods') .
            //" SET order_id = '$order_id' " .
            //"WHERE order_id " . db_create_in(array($main_order['order_id'], $slave_order['order_id']));
    //$GLOBALS['db']->query($sql);
    
    /* 插入订单商品并保留原有商品 */
    $sql = "INSERT INTO " . $GLOBALS['os']->table('order_goods') . "( " .
                "order_id, goods_id, goods_name, goods_sn, goods_number, market_price, ".
                "goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, color_id, size_id, send_number, is_rejected, goods_barcode) ".
            " SELECT '$order_id', goods_id, goods_name, goods_sn, goods_number, market_price, ".
                "goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, color_id, size_id, send_number, is_rejected, goods_barcode ".
            " FROM " .$GLOBALS['os']->table('order_goods') ." as g".
            " WHERE g.order_id " . db_create_in(array($main_order['order_id'], $slave_order['order_id']));
    $GLOBALS['db']->query($sql);
    
    /* 更新订单红包 */
    if($main_order['bonus_id'] >0 || $slave_order['bonus_id'] > 0){
    	/* 更新订单商品 */
    	$sql = 'UPDATE ' . $GLOBALS['os']->table('user_bonus') .
            	" SET order_id = '$order_id' " .
            	"WHERE order_id " . db_create_in(array($main_order['order_id'], $slave_order['order_id']));
    	$GLOBALS['db']->query($sql);
    }

    include_once(ROOT_PATH . 'includes/lib_clips.php');
    /* 插入支付日志 */
    insert_pay_log($order_id, $order['order_amount'], PAY_ORDER);

    $sql = 'select order_sn from '.$GLOBALS['os']->table('order_info').' where order_id = '.$order_id;
    $new_order_sn = $GLOBALS['db']->getOne($sql);
    
    /* 更新原来两个订单的状态为已合并 */
    $arr['order_status'] = OS_MERGED;
    $action_note = '合并主订单号'.$main_order['order_sn'].'和从订单号'.$slave_order['order_sn'].'并生成新的订单号'.$new_order_sn;
    
    update_order($main_order['order_id'], $arr);
    order_action($main_order['order_sn'], OS_MERGED, $main_order['shipping_status'], $main_order['pay_status'], $action_note);
    
    update_order($slave_order['order_id'], $arr);
    order_action($slave_order['order_sn'], OS_MERGED, $slave_order['shipping_status'], $slave_order['pay_status'], $action_note);

    /* 记录新订单的操作日志 */
    order_action($new_order_sn, $main_order['order_status'], SS_UNSHIPPED, $main_order['pay_status'], $action_note);
    
    if($main_order['process_status'] == OPS_SUSPEND && $slave_order['process_status'] == OPS_SUSPEND){
    	$sql = "INSERT INTO ".$os->table('order_suspend')." (relating_order_id, relating_order_sn, suspend_reason, from_user, add_time) VALUES ('".$order_id."', '".$new_order_sn."', '合并被挂起的订单','合并订单','$add_time')";
		$db->query($sql);
    }

    /* 返回成功 */
    return true;
}

/**
 * 订单拆分（目前单次仅支持拆分为2个子订单）
 * @param   int     订单ID 
 * @return  成功返回true，失败返回错误信息
 */
function split_order($original_order_id=0, $split_goods_rec_ids=array())
{
	global $db, $os;
	
	$result = array();
	if (!$original_order_id || count($split_goods_rec_ids) <= 0) {
		$result['code'] = -1;
		$result['message'] = '订单ID为空或未选择拆分商品。';
		return $result;
	}
	
	$goods_id_arr = array();
	$original_order_id = $original_order_id;
	$original_order = order_info($original_order_id);
	
	$sql = 'SELECT rec_id FROM ' . $os->table('order_goods') . ' WHERE order_id = ' . $original_order_id;
	$arr = $db->getAll($sql);
	
	foreach ($arr AS $value) {
		$goods_id_arr[] = $value['rec_id'];
	}

	$selected_goods_rec_id = $split_goods_rec_ids;
	$noselected_goods_rec_id = array_diff($goods_id_arr, $selected_goods_rec_id);
	
	$new_order_selected = $original_order;
	$new_order_noselected = $original_order;
	
	// 拆分选择的商品归于一张新的订单
	$new_order_selected['order_id'] = '';
	$new_order_selected['add_time'] = gmtime();
	$new_order_selected['process_status'] = OPS_SUSPEND;
	$new_order_selected['referer'] = '订单号'.$original_order['order_sn'].'拆分';
	$new_order_selected['bonus'] = 0;
	$new_order_selected['bonus_id'] = 0;
	$new_order_selected['surplus'] = 0;
	$new_order_selected['integral'] = 0;
	$new_order_selected['integral_money'] = 0;
	$new_order_selected['discount'] = 0;
    $new_order_selected['shipping_fee'] = 0;
    $new_order_selected['insure_fee'] = 0;
    $new_order_selected['pack_fee'] = 0;
    $new_order_selected['card_fee'] = 0;
    $new_order_selected['money_paid'] = 0;
    	
	do
	{
		$new_order_selected['order_sn'] = get_order_sn();
		if ($db->autoExecute($os->table('order_info'), $new_order_selected, 'INSERT', '', 'SILENT')) {
			break;
		} else {
			if ($db->errno() != 1062) {
				die($db->error());
			}
		}
	}
	while (true); // 防止订单号重复
	
	$new_order_selected_id = $db->insert_id();
	
    /* 插入订单商品并保留原有商品 */
    $sql = "INSERT INTO " . $GLOBALS['os']->table('order_goods') . "( " .
           "order_id, goods_id, goods_name, goods_sn, goods_number, market_price, ".
           "goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, color_id, size_id, send_number, is_rejected, goods_barcode) ".
           " SELECT '$new_order_selected_id', goods_id, goods_name, goods_sn, goods_number, market_price, ".
           "goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, color_id, size_id, send_number, is_rejected, goods_barcode "." FROM " .$GLOBALS['os']->table('order_goods') ." as g".
            " WHERE g.rec_id " . db_create_in($selected_goods_rec_id);
    $GLOBALS['db']->query($sql);
    
    $sql = 'SELECT SUM(goods_number) FROM '.$GLOBALS['os']->table('order_goods').' AS og WHERE og.order_id = '.$new_order_selected_id;
    $goods_count = $db->getOne($sql);

    /* 更新商品总金额和订单总金额 */
    update_order($new_order_selected_id, array('goods_amount' => order_amount($new_order_selected_id), 'order_amount' => order_amount($new_order_selected_id), 'goods_count' => $goods_count));
    update_order_amount($new_order_selected_id);

    /* 更新 pay_log */
    update_pay_log($new_order_selected_id);
    
	/* 把拆分后的订单放到挂起列表中 */
	$add_time = gmtime();
	$sql = "INSERT INTO ".$os->table('order_suspend')." (relating_order_id, relating_order_sn, suspend_reason, from_user, add_time) VALUES ('".$new_order_selected_id."', '".$new_order_selected['order_sn']."', '拆分订单".$original_order['order_sn']."','拆分订单','$add_time')";
	$db->query($sql);
	
	// 拆分未选择的商品归于一张新的订单
	$new_order_noselected['order_id'] = '';
	$new_order_noselected['add_time'] = gmtime();
	$new_order_noselected['process_status'] = OPS_SUSPEND;
	$new_order_noselected['referer'] = '订单号'.$original_order['order_sn'].'拆分';
	$new_order_noselected['bonus'] = 0;
	$new_order_noselected['bonus_id'] = 0;
	$new_order_noselected['surplus'] = 0;
	$new_order_noselected['integral'] = 0;
	$new_order_noselected['integral_money'] = 0;
	$new_order_noselected['discount'] = 0;
    $new_order_noselected['shipping_fee'] = 0;
    $new_order_noselected['insure_fee'] = 0;
    $new_order_noselected['pack_fee'] = 0;
    $new_order_noselected['card_fee'] = 0;
    $new_order_noselected['money_paid'] = 0;
    
	do
	{
		$new_order_noselected['order_sn'] = get_order_sn();
		if ($db->autoExecute($os->table('order_info'), $new_order_noselected, 'INSERT', '', 'SILENT')) {
			break;
		} else {
			if ($db->errno() != 1062) {
				die($db->error());
			}
		}
	}
	while (true); // 防止订单号重复
	
	$new_order_noselected_id = $db->insert_id();
	
    /* 插入订单商品并保留原有商品 */
    $sql = "INSERT INTO " . $GLOBALS['os']->table('order_goods') . "( " .
           "order_id, goods_id, goods_name, goods_sn, goods_number, market_price, ".
           "goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, color_id, size_id, send_number, is_rejected, goods_barcode) ".
           " SELECT '$new_order_noselected_id', goods_id, goods_name, goods_sn, goods_number, market_price, ".
           "goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, color_id, size_id, send_number, is_rejected, goods_barcode "." FROM " .$GLOBALS['os']->table('order_goods') ." as g".
            " WHERE g.rec_id " . db_create_in($noselected_goods_rec_id);
    $GLOBALS['db']->query($sql);

    $sql = 'SELECT SUM(goods_number) FROM '.$GLOBALS['os']->table('order_goods').' AS og WHERE og.order_id = '.$new_order_noselected_id;
    $goods_count = $db->getOne($sql);

    /* 更新商品总金额和订单总金额 */
    update_order($new_order_noselected_id, array('goods_amount' => order_amount($new_order_noselected_id), 'order_amount' => order_amount($new_order_noselected_id), 'goods_count' => $goods_count));
    update_order_amount($new_order_noselected_id);

    /* 更新 pay_log */
    update_pay_log($new_order_noselected_id);
    
    /* 把拆分后的订单放到挂起列表中 */
	$add_time = gmtime();
	$sql = "INSERT INTO ".$os->table('order_suspend')." (relating_order_id, relating_order_sn, suspend_reason, from_user, add_time) VALUES ('".$new_order_noselected_id."', '".$new_order_noselected['order_sn']."', '拆分订单".$original_order['order_sn']."','拆分订单','$add_time')";
	$db->query($sql);
    
    // 更新原有订单相关状态
    include_once(ROOT_PATH . 'includes/lib_clips.php');
    /* 插入支付日志 */
    insert_pay_log($new_order_selected_id, $new_order_selected['order_amount'], PAY_ORDER);
    insert_pay_log($new_order_noselected_id, $new_order_noselected['order_amount'], PAY_ORDER);

    /* 更新原来订单的状态为已拆分，拆分去向 */
    $arr['order_status'] = OS_SPLITED;
    $arr['split_to'] = $new_order_selected_id . ',' . $new_order_noselected_id;
    $action_note = '拆分主订单号'.$original_order['order_sn'].'生成新的订单号'.$new_order_selected['order_sn'].'和'.$new_order_noselected['order_sn'];
    
    update_order($original_order['order_id'], $arr);
    order_action($original_order['order_sn'], OS_SPLITED, $original_order['shipping_status'], $original_order['pay_status'], $action_note);
    
	/* 记录两张新订单的操作日志 */
    order_action($new_order_selected['order_sn'], $new_order_selected['order_status'], $new_order_selected['shipping_status'], $new_order_selected['pay_status'], $action_note);
    order_action($new_order_noselected['order_sn'], $new_order_noselected['order_status'], $new_order_noselected['shipping_status'], $new_order_noselected['pay_status'], $action_note);
    
    /* 退回原订单中支付的余额 */
    if ($original_order['user_id'] > 0 && $original_order['surplus'] > 0) {
		log_account_change($original_order['user_id'], $original_order['surplus'], 0, 0, 0, sprintf('由于拆分订单操作，退回支付订单 %s 时使用的预付款', $original_order['order_sn']));
    }
    
	 /* 退回原订单中支付的积分 */
	if ($original_order['user_id'] > 0 && $original_order['integral'] > 0) {
		log_account_change($original_order['user_id'], 0, 0, 0, $original_order['integral'], sprintf('由于拆分订单操作，退回支付订单 %s 时使用的积分', $original_order['order_sn']));
	}
	
	/* 退回原订单中支付的红包 */
	if ($original_order['bonus_id'] > 0) {
		unuse_bonus($original_order['bonus_id']);
	}
	
	/* 退回原订单相关金额 */
	$arr = array(
		'bonus_id'  => 0,
		'bonus'     => 0,
		'integral'  => 0,
		'surplus'   => 0,
		'integral_money'    => 0,
		'discount' =>  0,
	    'shipping_fee' => 0,
	    'insure_fee' => 0,
	    'pack_fee' => 0,
	    'card_fee' => 0,
	    'money_paid' => 0,	
		'order_amount' => $original_order['goods_amount']
	);
	update_order($original_order['order_id'], $arr);
	
	/* 更新新订单配货状态 */
	if ($original_order['range_status'] == ORS_ERROR || $original_order['range_status'] == ORS_OUT) {
		$GLOBALS['db']->query("UPDATE " . $GLOBALS['os']->table('order_info') . " SET range_status='" . ORS_UNCONFIRMED . "' WHERE order_id IN ( $new_order_selected_id,$new_order_noselected_id )");
	}
	/* 清除配货未成功订单记录 */
	$GLOBALS['db']->query("DELETE FROM " . $GLOBALS['os']->table('order_out') . " WHERE relating_order_id='{$original_order_id}'");
	
	$result['code'] = 0;
	$result['new_order_id'] = $new_order_selected_id;
	$result['message'] = '订单拆分成功。';
	
	return $result;
}

/**
 * 查询配送区域属于哪个办事处管辖
 * @param   array   $regions    配送区域（1、2、3、4级按顺序）
 * @return  int     办事处id，可能为0
 */
function get_agency_by_regions($regions)
{
    if (!is_array($regions) || empty($regions))
    {
        return 0;
    }

    $arr = array();
    $sql = "SELECT region_id, agency_id " .
            "FROM " . $GLOBALS['os']->table('region') .
            " WHERE region_id " . db_create_in($regions) .
            " AND region_id > 0 AND agency_id > 0";
    $res = $GLOBALS['db']->query($sql);
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $arr[$row['region_id']] = $row['agency_id'];
    }
    if (empty($arr))
    {
        return 0;
    }

    $agency_id = 0;
    for ($i = count($regions) - 1; $i >= 0; $i--)
    {
        if (isset($arr[$regions[$i]]))
        {
            return $arr[$regions[$i]];
        }
    }
}

/**
 * 获取配送插件的实例
 * @param   int   $shipping_id    配送插件ID
 * @return  object     配送插件对象实例
 */
function &get_shipping_object($shipping_id)
{
    $shipping  = shipping_info($shipping_id);
    if (!$shipping)
    {
        $object = new stdClass();
        return $object;
    }

    $file_path = ROOT_PATH.'includes/modules/shipping/' . $shipping['shipping_code'] . '.php';

    include_once($file_path);

    $object = new $shipping['shipping_code'];
    return $object;
}

/**
 * 改变订单中商品库存
 * @param   int     $order_id   订单号
 * @param   bool    $is_dec     是否减少库存
 */
function change_order_goods_storage($order_id, $is_dec = true)
{
    /* 查询订单商品信息 */
    $sql = "SELECT goods_id, SUM(goods_number) AS num, max(extension_code) as extension_code FROM " . $GLOBALS['os']->table('order_goods') .
            " WHERE order_id = '$order_id' AND is_real = 1 GROUP BY goods_id ";
    $res = $GLOBALS['db']->query($sql);
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        if ($row['extension_code'] != "package_buy")
        {
            if ($is_dec)
            {
                $sql = "UPDATE " . $GLOBALS['os']->table('goods') .
                        " SET goods_number = goods_number - '" . $row['num'] . "' " .
                        " WHERE goods_id = '" . $row['goods_id'] . "' LIMIT 1";
            }
            else
            {
                $sql = "UPDATE " . $GLOBALS['os']->table('goods') .
                        " SET goods_number = goods_number + '" . $row['num'] . "' " .
                        " WHERE goods_id = '" . $row['goods_id'] . "' LIMIT 1";
            }
            $GLOBALS['db']->query($sql);
        }
    }
}

/**
 * 取得支付方式id列表
 * @param   bool    $is_cod 是否货到付款
 * @return  array
 */
function payment_id_list($is_cod)
{
    $sql = "SELECT pay_id FROM " . $GLOBALS['os']->table('payment');
    if ($is_cod)
    {
        $sql .= " WHERE is_cod = 1";
    }
    else
    {
        $sql .= " WHERE is_cod = 0";
    }

    return $GLOBALS['db']->getCol($sql);
}

/**
 * 生成查询订单的sql
 * @param   string  $type   类型
 * @param   string  $alias  order表的别名（包括.例如 o.）
 * @return  string
 */
function order_query_sql($type = 'finished', $alias = '')
{
    /* 已完成订单 */
    if ($type == 'finished')
    {
        return " AND {$alias}order_status = '" . OS_CONFIRMED . "'" .
               " AND {$alias}shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) .
               " AND {$alias}pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) . " ";
    }
    /* 待发货订单 */
    elseif ($type == 'await_ship')
    {
        return " AND   {$alias}order_status = '" . OS_CONFIRMED . "'" .
               " AND   {$alias}shipping_status " . db_create_in(array(SS_UNSHIPPED, SS_PREPARING)) .
               " AND ( {$alias}pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) . " OR {$alias}pay_id " . db_create_in(payment_id_list(true)) . ") ";
    }
    /* 待付款订单 */
    elseif ($type == 'await_pay')
    {
        return " AND   {$alias}order_status = '" . OS_CONFIRMED . "'" .
               " AND   {$alias}pay_status = '" . PS_UNPAYED . "'" .
               " AND ( {$alias}shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) . " OR {$alias}pay_id " . db_create_in(payment_id_list(false)) . ") ";
    }
    /* 未确认订单 */
    elseif ($type == 'unconfirmed')
    {
        return " AND {$alias}order_status = '" . OS_UNCONFIRMED . "' ";
    }
    /* 未处理订单：用户可操作 */
    elseif ($type == 'unprocessed')
    {
        return " AND {$alias}order_status " . db_create_in(array(OS_UNCONFIRMED, OS_CONFIRMED)).
               " AND {$alias}shipping_status = '" . SS_UNSHIPPED . "'" .
               " AND {$alias}pay_status   " . db_create_in(array(PS_UNPAYED, PS_PAYED));
    }
    /* 未付款未发货订单：管理员可操作 */
    elseif ($type == 'unpay_unship')
    {
        return " AND {$alias}order_status " . db_create_in(array(OS_UNCONFIRMED, OS_CONFIRMED)) .
               " AND {$alias}shipping_status " . db_create_in(array(SS_UNSHIPPED, SS_PREPARING)) .
               " AND {$alias}pay_status = '" . PS_UNPAYED . "' ";
    }
    /* 已发货订单：不论是否付款 */
    elseif ($type == 'shipped')
    {
        return " AND {$alias}order_status = '" . OS_CONFIRMED . "'" .
               " AND {$alias}shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) . " ";
    }
    else
    {
        die('函数 order_query_sql 参数错误');
    }
}

/**
 * 生成查询订单总金额的字段
 * @param   string  $alias  order表的别名（包括.例如 o.）
 * @return  string
 */
function order_amount_field($alias = '')
{
    return "   {$alias}goods_amount + {$alias}tax + {$alias}shipping_fee" .
           " + {$alias}insure_fee + {$alias}pay_fee + {$alias}pack_fee" .
           " + {$alias}card_fee ";
}

/**
 * 生成计算应付款金额的字段
 * @param   string  $alias  order表的别名（包括.例如 o.）
 * @return  string
 */
function order_due_field($alias = '')
{
    return order_amount_field($alias) .
            " - {$alias}money_paid - {$alias}surplus - {$alias}integral_money" .
            " - {$alias}bonus - {$alias}discount ";
}

/**
 * 计算折扣：根据购物车和优惠活动
 * @return  float   折扣
 */
function compute_discount()
{
    /* 查询优惠活动 */
    $now = gmtime();
    $user_rank = ',' . $_SESSION['user_rank'] . ',';
    $sql = "SELECT * " .
            "FROM " . $GLOBALS['os']->table('favourable_activity') .
            " WHERE start_time <= '$now'" .
            " AND end_time >= '$now'" .
            " AND CONCAT(',', user_rank, ',') LIKE '%" . $user_rank . "%'" .
            " AND act_type " . db_create_in(array(FAT_DISCOUNT, FAT_PRICE));
    $favourable_list = $GLOBALS['db']->getAll($sql);
    if (!$favourable_list)
    {
        return 0;
    }

    /* 查询购物车商品 */
    $sql = "SELECT c.goods_id, c.goods_price * c.goods_number AS subtotal, g.cat_id, g.brand_id " .
            "FROM " . $GLOBALS['os']->table('cart') . " AS c, " . $GLOBALS['os']->table('goods') . " AS g " .
            "WHERE c.goods_id = g.goods_id " .
            "AND c.session_id = '" . SESS_ID . "' " .
            "AND c.parent_id = 0 " .
            "AND c.is_gift = 0 " .
            "AND rec_type = '" . CART_GENERAL_GOODS . "'";
    $goods_list = $GLOBALS['db']->getAll($sql);
    if (!$goods_list)
    {
        return 0;
    }

    /* 初始化折扣 */
    $discount = 0;
    $favourable_name = array();

    /* 循环计算每个优惠活动的折扣 */
    foreach ($favourable_list as $favourable)
    {
        $total_amount = 0;
        if ($favourable['act_range'] == FAR_ALL)
        {
            foreach ($goods_list as $goods)
            {
                $total_amount += $goods['subtotal'];
            }
        }
        elseif ($favourable['act_range'] == FAR_CATEGORY)
        {
            /* 找出分类id的子分类id */
            $id_list = array();
            $raw_id_list = explode(',', $favourable['act_range_ext']);
            foreach ($raw_id_list as $id)
            {
                $id_list = array_merge($id_list, array_keys(cat_list($id, 0, false)));
            }
            $ids = join(',', array_unique($id_list));

            foreach ($goods_list as $goods)
            {
                if (strpos(',' . $ids . ',', ',' . $goods['cat_id'] . ',') !== false)
                {
                    $total_amount += $goods['subtotal'];
                }
            }
        }
        elseif ($favourable['act_range'] == FAR_BRAND)
        {
            foreach ($goods_list as $goods)
            {
                if (strpos(',' . $favourable['act_range_ext'] . ',', ',' . $goods['brand_id'] . ',') !== false)
                {
                    $total_amount += $goods['subtotal'];
                }
            }
        }
        elseif ($favourable['act_range'] == FAR_GOODS)
        {
            foreach ($goods_list as $goods)
            {
                if (strpos(',' . $favourable['act_range_ext'] . ',', ',' . $goods['goods_id'] . ',') !== false)
                {
                    $total_amount += $goods['subtotal'];
                }
            }
        }
        else
        {
            continue;
        }

        /* 如果金额满足条件，累计折扣 */
        if ($total_amount > 0 && $total_amount >= $favourable['min_amount'] && ($total_amount <= $favourable['max_amount'] || $favourable['max_amount'] == 0))
        {
            if ($favourable['act_type'] == FAT_DISCOUNT)
            {
                $discount += $total_amount * (1 - $favourable['act_type_ext'] / 100);

                $favourable_name[] = $favourable['act_name'];
            }
            elseif ($favourable['act_type'] == FAT_PRICE)
            {
                $discount += $favourable['act_type_ext'];

                $favourable_name[] = $favourable['act_name'];
            }
        }
    }

    return array('discount' => $discount, 'name' => $favourable_name);
}

/**
 * 取得购物车该赠送的积分数
 * @return  int     积分数
 */
function get_give_integral()
{
        $sql = "SELECT SUM(c.goods_number * IF(g.give_integral > -1, g.give_integral, c.goods_price))" .
                "FROM " . $GLOBALS['os']->table('cart') . " AS c, " .
                          $GLOBALS['os']->table('goods') . " AS g " .
                "WHERE c.goods_id = g.goods_id " .
                "AND c.session_id = '" . SESS_ID . "' " .
                "AND c.goods_id > 0 " .
                "AND c.parent_id = 0 " .
                "AND c.rec_type = 0 " .
                "AND c.is_gift = 0";
        //die($sql);
        return intval($GLOBALS['db']->getOne($sql));
}

/**
 * 取得某订单应该赠送的积分数
 * @param   array   $order  订单
 * @return  int     积分数
 */
function integral_to_give($order)
{
    /* 判断是否团购 */
    if ($order['extension_code'] == 'group_buy')
    {
        include_once(ROOT_PATH . 'includes/lib_goods.php');
        $group_buy = group_buy_info(intval($order['extension_id']));

        return array('custom_points' => $group_buy['gift_integral'], 'rank_points' => $order['goods_amount']);
    }
    else
    {
        $sql = "SELECT SUM(og.goods_number * IF(g.give_integral > -1, g.give_integral, og.goods_price)) AS custom_points, SUM(og.goods_number * IF(g.rank_integral > -1, g.rank_integral, og.goods_price)) AS rank_points " .
                "FROM " . $GLOBALS['os']->table('order_goods') . " AS og, " .
                          $GLOBALS['os']->table('goods') . " AS g " .
                "WHERE og.goods_id = g.goods_id " .
                "AND og.order_id = '$order[order_id]' " .
                "AND og.goods_id > 0 " .
                "AND og.parent_id = 0 " .
                "AND og.is_gift = 0";

        return $GLOBALS['db']->getRow($sql);
    }
}

/**
 * 发红包：发货时发红包
 * @param   int     $order_id   订单号
 * @return  bool
 */
function send_order_bonus($order_id)
{
    /* 取得订单应该发放的红包 */
    $bonus_list = order_bonus($order_id);

    /* 如果有红包，统计并发送 */
    if ($bonus_list)
    {
        /* 用户信息 */
        $sql = "SELECT u.user_id, u.user_name, u.email " .
                "FROM " . $GLOBALS['os']->table('order_info') . " AS o, " .
                          $GLOBALS['os']->table('users') . " AS u " .
                "WHERE o.order_id = '$order_id' " .
                "AND o.user_id = u.user_id ";
        $user = $GLOBALS['db']->getRow($sql);

        /* 统计 */
        $count = 0;
        $money = '';
        foreach ($bonus_list AS $bonus)
        {
            $count += $bonus['number'];
            $money .= price_format($bonus['type_money']) . ' [' . $bonus['number'] . '], ';

            /* 修改用户红包 */
            $sql = "INSERT INTO " . $GLOBALS['os']->table('user_bonus') . " (bonus_type_id, user_id) " .
                    "VALUES('$bonus[type_id]', '$user[user_id]')";
            for ($i = 0; $i < $bonus['number']; $i++)
            {
                if (!$GLOBALS['db']->query($sql))
                {
                    return $GLOBALS['db']->errorMsg();
                }
            }
        }

        /* 如果有红包，发送邮件 */
        if ($count > 0)
        {
            $tpl = get_mail_template('send_bonus');
            $GLOBALS['smarty']->assign('user_name', $user['user_name']);
            $GLOBALS['smarty']->assign('count', $count);
            $GLOBALS['smarty']->assign('money', $money);
            $GLOBALS['smarty']->assign('shop_name', $GLOBALS['_CFG']['shop_name']);
            $GLOBALS['smarty']->assign('send_date', local_date($GLOBALS['_CFG']['date_format']));
            $GLOBALS['smarty']->assign('sent_date', local_date($GLOBALS['_CFG']['date_format']));
            $content = $GLOBALS['smarty']->fetch('str:' . $tpl['template_content']);
            send_mail($user['user_name'], $user['email'], $tpl['template_subject'], $content, $tpl['is_html']);
        }
    }

    return true;
}

/**
 * 返回订单发放的红包
 * @param   int     $order_id   订单id
 */
function return_order_bonus($order_id)
{
    /* 取得订单应该发放的红包 */
    $bonus_list = order_bonus($order_id);

    /* 删除 */
    if ($bonus_list)
    {
        /* 取得订单信息 */
        $order = order_info($order_id);
        $user_id = $order['user_id'];

        foreach ($bonus_list AS $bonus)
        {
            $sql = "DELETE FROM " . $GLOBALS['os']->table('user_bonus') .
                    " WHERE bonus_type_id = '$bonus[type_id]' " .
                    "AND user_id = '$user_id' " .
                    "AND order_id = '0' LIMIT " . $bonus['number'];
            $GLOBALS['db']->query($sql);
        }
    }
}

/**
 * 取得订单应该发放的红包
 * @param   int     $order_id   订单id
 * @return  array
 */
function order_bonus($order_id)
{
    /* 查询按商品发的红包 */
    $day    = getdate();
    $today  = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);

    $sql = "SELECT b.type_id, b.type_money, SUM(o.goods_number) AS number " .
            "FROM " . $GLOBALS['os']->table('order_goods') . " AS o, " .
                      $GLOBALS['os']->table('goods') . " AS g, " .
                      $GLOBALS['os']->table('bonus_type') . " AS b " .
            " WHERE o.order_id = '$order_id' " .
            " AND o.is_gift = 0 " .
            " AND o.goods_id = g.goods_id " .
            " AND g.bonus_type_id = b.type_id " .
            " AND b.send_type = '" . SEND_BY_GOODS . "' " .
            " AND b.send_start_date <= '$today' " .
            " AND b.send_end_date >= '$today' " .
            " GROUP BY b.type_id ";
    $list = $GLOBALS['db']->getAll($sql);

    /* 查询定单中非赠品总金额 */
    $amount = order_amount($order_id, false);

    /* 查询订单日期 */
    $sql = "SELECT add_time " .
            " FROM " . $GLOBALS['os']->table('order_info') .
            " WHERE order_id = '$order_id' LIMIT 1";
    $order_time = $GLOBALS['db']->getOne($sql);

    /* 查询按订单发的红包 */
    $sql = "SELECT type_id, type_money, IFNULL(FLOOR('$amount' / min_amount), 1) AS number " .
            "FROM " . $GLOBALS['os']->table('bonus_type') .
            "WHERE send_type = '" . SEND_BY_ORDER . "' " .
            "AND send_start_date <= '$order_time' " .
            "AND send_end_date >= '$order_time' ";
    $list = array_merge($list, $GLOBALS['db']->getAll($sql));

    return $list;
}

/**
 * 计算购物车中的商品能享受红包支付的总额
 * @return  float   享受红包支付的总额
 */
function compute_discount_amount()
{
    /* 查询优惠活动 */
    $now = gmtime();
    $user_rank = ',' . $_SESSION['user_rank'] . ',';
    $sql = "SELECT *" .
            "FROM " . $GLOBALS['os']->table('favourable_activity') .
            " WHERE start_time <= '$now'" .
            " AND end_time >= '$now'" .
            " AND CONCAT(',', user_rank, ',') LIKE '%" . $user_rank . "%'" .
            " AND act_type " . db_create_in(array(FAT_DISCOUNT, FAT_PRICE));
    $favourable_list = $GLOBALS['db']->getAll($sql);
    if (!$favourable_list)
    {
        return 0;
    }

    /* 查询购物车商品 */
    $sql = "SELECT c.goods_id, c.goods_price * c.goods_number AS subtotal, g.cat_id, g.brand_id " .
            "FROM " . $GLOBALS['os']->table('cart') . " AS c, " . $GLOBALS['os']->table('goods') . " AS g " .
            "WHERE c.goods_id = g.goods_id " .
            "AND c.session_id = '" . SESS_ID . "' " .
            "AND c.parent_id = 0 " .
            "AND c.is_gift = 0 " .
            "AND rec_type = '" . CART_GENERAL_GOODS . "'";
    $goods_list = $GLOBALS['db']->getAll($sql);
    if (!$goods_list)
    {
        return 0;
    }

    /* 初始化折扣 */
    $discount = 0;
    $favourable_name = array();

    /* 循环计算每个优惠活动的折扣 */
    foreach ($favourable_list as $favourable)
    {
        $total_amount = 0;
        if ($favourable['act_range'] == FAR_ALL)
        {
            foreach ($goods_list as $goods)
            {
                $total_amount += $goods['subtotal'];
            }
        }
        elseif ($favourable['act_range'] == FAR_CATEGORY)
        {
            /* 找出分类id的子分类id */
            $id_list = array();
            $raw_id_list = explode(',', $favourable['act_range_ext']);
            foreach ($raw_id_list as $id)
            {
                $id_list = array_merge($id_list, array_keys(cat_list($id, 0, false)));
            }
            $ids = join(',', array_unique($id_list));

            foreach ($goods_list as $goods)
            {
                if (strpos(',' . $ids . ',', ',' . $goods['cat_id'] . ',') !== false)
                {
                    $total_amount += $goods['subtotal'];
                }
            }
        }
        elseif ($favourable['act_range'] == FAR_BRAND)
        {
            foreach ($goods_list as $goods)
            {
                if (strpos(',' . $favourable['act_range_ext'] . ',', ',' . $goods['brand_id'] . ',') !== false)
                {
                    $total_amount += $goods['subtotal'];
                }
            }
        }
        elseif ($favourable['act_range'] == FAR_GOODS)
        {
            foreach ($goods_list as $goods)
            {
                if (strpos(',' . $favourable['act_range_ext'] . ',', ',' . $goods['goods_id'] . ',') !== false)
                {
                    $total_amount += $goods['subtotal'];
                }
            }
        }
        else
        {
            continue;
        }
    }

    return $total_amount;
}

/**
 * 添加礼包到购物车
 *
 * @access  public
 * @param   integer $package_id   礼包编号
 * @param   integer $num          礼包数量
 * @return  boolean
 */
function add_package_to_cart($package_id, $num = 1)
{
    $GLOBALS['err']->clean();

    /* 取得礼包信息 */
    $package = get_package_info($package_id);

    if (empty($package))
    {
        $GLOBALS['err']->add($GLOBALS['_LANG']['goods_not_exists'], ERR_NOT_EXISTS);

        return false;
    }

    /* 是否正在销售 */
    if ($package['is_on_sale'] == 0)
    {
        $GLOBALS['err']->add('对不起，该商品已经下架。', ERR_NOT_ON_SALE);

        return false;
    }

    /* 检查库存 */
//    if ($GLOBALS['_CFG']['use_storage'] == 1 && $num > $package['goods_number'])
//    {
//        $num = $goods['goods_number'];
//        $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['shortage'], $num), ERR_OUT_OF_STOCK);
//
//        return false;
//    }

    /* 初始化要插入购物车的基本件数据 */
    $parent = array(
        'user_id'       => $_SESSION['user_id'],
        'session_id'    => SESS_ID,
        'goods_id'      => $package_id,
        'goods_sn'      => '',
        'goods_name'    => addslashes($package['package_name']),
        'market_price'  => $package['market_package'],
        'goods_price'   => $package['package_price'],
        'goods_number'  => $num,
        'goods_attr'    => '',
        'goods_attr_id' => '',
        'is_real'       => $package['is_real'],
        'extension_code'=> 'package_buy',
        'is_gift'       => 0,
        'rec_type'      => CART_GENERAL_GOODS
    );

    /* 如果数量不为0，作为基本件插入 */
    if ($num > 0)
    {
         /* 检查该商品是否已经存在在购物车中 */
        $sql = "SELECT goods_number FROM " .$GLOBALS['os']->table('cart').
                " WHERE session_id = '" .SESS_ID. "' AND goods_id = '" . $package_id . "' ".
                " AND parent_id = 0 AND extension_code = 'package_buy' " .
                " AND rec_type = '" . CART_GENERAL_GOODS . "'";

        $row = $GLOBALS['db']->getRow($sql);

        if($row) //如果购物车已经有此物品，则更新
        {
            $num += $row['goods_number'];
            if ($GLOBALS['_CFG']['use_storage'] == 0 || $num > 0)
            {
                $sql = "UPDATE " . $GLOBALS['os']->table('cart') . " SET goods_number = '" . $num . "'" .
                       " WHERE session_id = '" .SESS_ID. "' AND goods_id = '$package_id' ".
                       " AND parent_id = 0 AND extension_code = 'package_buy' " .
                       " AND rec_type = '" . CART_GENERAL_GOODS . "'";
                $GLOBALS['db']->query($sql);
            }
            else
            {
                $GLOBALS['err']->add(sprintf("对不起，该商品已经库存不足暂停销售。\n你现在要进行缺货登记来预订该商品吗？", $num), ERR_OUT_OF_STOCK);
                return false;
            }
        }
        else //购物车没有此物品，则插入
        {
            $GLOBALS['db']->autoExecute($GLOBALS['os']->table('cart'), $parent, 'INSERT');
        }
    }

    /* 把赠品删除 */
    $sql = "DELETE FROM " . $GLOBALS['os']->table('cart') . " WHERE session_id = '" . SESS_ID . "' AND is_gift <> 0";
    $GLOBALS['db']->query($sql);

    return true;
}

/**
 * Openshop订单批量配货接口
 * 
 * @param   int / string 	$order_id	订单号 / 订单号集
 * @param 	bool			$exit		是否出错停止
 * @return  true / false
 */
function range_orders($order_id = '', $exit = false) {
	if (!$GLOBALS['_CFG']['use_ors'] || !$order_id) { return false; }
	
	/* 初始化数组 */
	$result = array();
	$result['success_sns'] = array();
	$result['error_sns'] = array();
	$result['out_sns'] = array();
	$result['other_sns'] = array();
	$result['invalid_sns'] = array();
	$valid_ids = array();
	$valid_sns = array();

	/* 进行配货操作 */
	if ($order_id) {
		//待配货列表配置选项
		if ($GLOBALS['_CFG']['in_range_options'] == 0) {
			$status_str = " order_status = '" . OS_CONFIRMED . "' ";
		} elseif ($GLOBALS['_CFG']['in_range_options'] == 1) {
			$status_str = " order_status = '" . OS_CONFIRMED . "' AND pay_status = '" . PS_PAYED . "' ";
		} elseif ($GLOBALS['_CFG']['in_range_options'] == 2) {
			$status_str = " order_status = '" . OS_CONFIRMED . "' OR ( order_status = '" . OS_UNCONFIRMED . "' AND pay_status = '" . PS_PAYED . "' ) ";
		} elseif ($GLOBALS['_CFG']['in_range_options'] == 3) {
			$status_str = " order_status = '" . OS_CONFIRMED . "' AND ( order_status = '" . OS_UNCONFIRMED . "' AND pay_status = '" . PS_PAYED . "' ) ";
		} else {
			$status_str = " order_status = '" . OS_CONFIRMED . "' OR ( order_status = '" . OS_UNCONFIRMED . "' AND pay_status = '" . PS_PAYED . "' ) ";
		}
		$search_str = " AND user_id>'0' AND ( $status_str ) AND shipping_status = ".SS_UNSHIPPED." AND process_status = ".OPS_NORMAL." AND range_status = ".ORS_UNCONFIRMED." ";
		$valid_ids = $GLOBALS['db']->getCol("SELECT order_id FROM " . $GLOBALS['os']->table('order_info') . " WHERE order_sn IN ( $order_id ) $search_str ");
		if (count($valid_ids) > 0) {
			$in_str = " AND oi.order_id IN ( " . implode(',', $valid_ids) . " ) ";
			$not_in_str = " AND order_id NOT IN ( " . implode(',', $valid_ids) . " ) ";
		} else {
			$in_str = '';
			$not_in_str = '';
		}
		/* 设置配货顺序 */
		if ($GLOBALS['_CFG']['use_ors'] && count($valid_ids) > 0) {
			if ($GLOBALS['_CFG']['ors_sort'] == 1) { $order_by_str = ' ORDER BY u.pay_points DESC '; }
			elseif ($GLOBALS['_CFG']['ors_sort'] == 2) { $order_by_str = ' ORDER BY oi.add_time ASC '; }
			elseif ($GLOBALS['_CFG']['ors_sort'] == 3) { $order_by_str = ' ORDER BY oi.pay_time ASC '; }
			else { $order_by_str = ' ORDER BY oi.order_id ASC '; }
			$valid_ids = $GLOBALS['db']->getCol("SELECT oi.order_id FROM " . $GLOBALS['os']->table('order_info') . " AS oi, " . $GLOBALS['os']->table('users') . " AS u WHERE oi.user_id=u.user_id $in_str $order_by_str ");
		}
		if (count($valid_ids) > 0) {
			$result = manage_goods_inventory($valid_ids, 'range');
		}
		$result['invalid_sns'] = $GLOBALS['db']->getCol("SELECT order_sn FROM " . $GLOBALS['os']->table('order_info') . " WHERE user_id>'0' AND order_sn IN ( $order_id ) $not_in_str ");
	} else {
		if ($exit) { sys_msg('请先勾选需要配货的订单。'); exit; }
		else { return false; }
	}
	
	/* 修改订单状态 */
	if (is_array($result['success_sns'])) {
		foreach($result['success_sns'] as $key => $val) {
			$order = order_info(0, $val);
			/* 标记配货状态为已配货 */
			update_order($order['order_id'], array('range_status' => ORS_CONFIRMED, 'range_time' => gmtime()));
			order_action($order['order_sn'], $order['order_status'], $order['shipping_status'], $order['pay_status'], $action_note, $_SESSION['admin_name'], ORS_CONFIRMED);
			/* 清除配货未成功订单记录 */
			$GLOBALS['db']->query("DELETE FROM " . $GLOBALS['os']->table('order_out') . " WHERE relating_order_id = '" . $order['order_id'] . "'");
			/* 更新计划发货时间 */
			auto_update_shipping_delivery($order['order_id']);
		}
	}
	if (is_array($result['error_sns'])) {
		foreach($result['error_sns'] as $key => $val) {
			$order = order_info(0, $val);
			/* 标记配货状态为失败 */
			update_order($order['order_id'], array('range_status' => ORS_ERROR));
			order_action($order['order_sn'], $order['order_status'], $order['shipping_status'], $order['pay_status'], '配货失败', $_SESSION['admin_name'], ORS_ERROR);
			/* 记录缺货订单 */
			$add_time = gmtime();
			if($id = $GLOBALS['db']->getOne("SELECT id FROM " . $GLOBALS['os']->table('order_out') . " WHERE relating_order_id='" . $order['order_id'] . "'")) {
				$sql = "UPDATE " . $GLOBALS['os']->table('order_out') . " SET process_status='" . ORS_ERROR . "' WHERE id='{$id}'";
			} else {
				$sql = "INSERT INTO ".$GLOBALS['os']->table('order_out')." (relating_order_id, relating_order_sn, out_reason, process_user, process_status, from_user, add_time) VALUES ('".$order['order_id']."', '".$order['order_sn']."', '', '".$_SESSION['admin_name']."', '" . ORS_ERROR . "', '配货未成功', '$add_time')";
			}
			$GLOBALS['db']->query($sql);
		}
	}
	if (is_array($result['out_sns'])) {
		foreach($result['out_sns'] as $key => $val) {
			$order = order_info(0, $val);
			/* 标记配货状态为缺货 */
			update_order($order['order_id'], array('range_status' => ORS_OUT));
			order_action($order['order_sn'], $order['order_status'], $order['shipping_status'], $order['pay_status'], '缺货', $_SESSION['admin_name'], ORS_OUT);
			/* 记录缺货订单 */
			$add_time = gmtime();
			if($id = $GLOBALS['db']->getOne("SELECT id FROM " . $GLOBALS['os']->table('order_out') . " WHERE relating_order_id='" . $order['order_id'] . "'")) {
				$sql = "UPDATE " . $GLOBALS['os']->table('order_out') . " SET process_status='" . ORS_OUT . "' WHERE id='{$id}'";
			} else {
				$sql = "INSERT INTO ".$GLOBALS['os']->table('order_out')." (relating_order_id, relating_order_sn, out_reason, process_user, process_status, from_user, add_time) VALUES ('".$order['order_id']."', '".$order['order_sn']."', '', '".$_SESSION['admin_name']."', '" . ORS_OUT . "', '配货未成功', '$add_time')";
			}
			$GLOBALS['db']->query($sql);
		}
	}
	
	return $result;
}

/**
 * Openshop单张订单配货接口 
 * 
 * @param   int 	$order_id	订单号
 * @param   bool  	$exit		是否出错停止
 * @return  true / false
 */
function range_order($order_id = 0, $exit = false) {
	if (!$GLOBALS['_CFG']['use_ors'] || !$order_id) { return false; }
	
	//待配货列表配置选项
	if ($GLOBALS['_CFG']['in_range_options'] == 0) {
		$status_str = " order_status = '" . OS_CONFIRMED . "' ";
	} elseif ($GLOBALS['_CFG']['in_range_options'] == 1) {
		$status_str = " order_status = '" . OS_CONFIRMED . "' AND pay_status = '" . PS_PAYED . "' ";
	} elseif ($GLOBALS['_CFG']['in_range_options'] == 2) {
		$status_str = " order_status = '" . OS_CONFIRMED . "' OR ( order_status = '" . OS_UNCONFIRMED . "' AND pay_status = '" . PS_PAYED . "' ) ";
	} elseif ($GLOBALS['_CFG']['in_range_options'] == 3) {
		$status_str = " order_status = '" . OS_CONFIRMED . "' AND ( order_status = '" . OS_UNCONFIRMED . "' AND pay_status = '" . PS_PAYED . "' ) ";
	} else {
		$status_str = " order_status = '" . OS_CONFIRMED . "' OR ( order_status = '" . OS_UNCONFIRMED . "' AND pay_status = '" . PS_PAYED . "' ) ";
	}
	$search_str = " AND user_id>'0' AND ( $status_str ) AND shipping_status = ".SS_UNSHIPPED." AND process_status = ".OPS_NORMAL." AND range_status = ".ORS_UNCONFIRMED." ";
	
	//判断订单状态
	if (!$GLOBALS['db']->getOne("SELECT order_id FROM " . $GLOBALS['os']->table('order_info') . " WHERE 1=1 $search_str ")) {
		return false;
	} else {
		$order = order_info($order_id);
	}
	
	/* 库存处理 */
	$result = manage_good_inventory($order['order_id'], 'range');
	
	if (is_array($result)) {
		if ($result['code'] == 0) {
			/* 清除配货未成功订单记录 */
			$GLOBALS['db']->query("DELETE FROM " . $GLOBALS['os']->table('order_out') . " WHERE relating_order_id='" . $order['order_id'] . "'");
		} else {
			/* 标记配货状态为失败or缺货 */
			update_order($order_id, array('range_status' => $result['code']));
			order_action($order['order_sn'], $order['order_status'], $order['shipping_status'], $order['pay_status'], $result['msg'], $_SESSION['admin_name'], $result['code']);
			/* 记录缺货订单 */
			$add_time = gmtime();
			if($id = $GLOBALS['db']->getOne("SELECT id FROM " . $os->table('order_out') . " WHERE relating_order_id='" . $order['order_id'] . "'")) {
				$sql = "UPDATE " . $os->table('order_out') . " SET process_status='" . $result['code'] . "' WHERE id='{$id}'";
			} else {
				$sql = "INSERT INTO ".$os->table('order_out')." (relating_order_id, relating_order_sn, out_reason, process_user, process_status, from_user, add_time) VALUES ('".$order['order_id']."', '".$order['order_sn']."', '', '".$_SESSION['admin_name']."', '" . $result['code'] . "', '配货未成功', '$add_time')";
			}
			$GLOBALS['db']->query($sql);
			
			if ($exit) { sys_msg($result['message']); exit; }
			else { return $result; }
		}
	} else {
		if ($result) {
			/* 清除配货未成功订单记录 */
			$GLOBALS['db']->query("DELETE FROM " . $GLOBALS['os']->table('order_out') . " WHERE relating_order_id='" . $order['order_id'] . "'");
		} else {
			if ($exit) { sys_msg('库存处理失败，请核对。'); exit; }
			else { return $result; }
		}
	}
	
	$log_already = order_action_judge($order['order_sn'], $order['order_status'], $order['shipping_status'], $order['pay_status'], $action_note, '', ORS_CONFIRMED);
	if ($log_already) {
		os_header("Location: order.php?act=info&order_id=".$order_id. "\n");
		exit;
	} else {
		/* 标记配货状态为已配货 */
		update_order($order_id, array('range_status' => ORS_CONFIRMED));
		/* 记录log */
		order_action($order['order_sn'], $order['order_status'], $order['shipping_status'], $order['pay_status'], $action_note, $_SESSION['admin_name'], ORS_CONFIRMED);
		/* 更新计划发货时间 */
		auto_update_shipping_delivery($order['order_id']);
	}
	
	return true;
}

/**
 * 批量管理Openshop的订单商品库存公用接口
 * 
 * @param   int / array 	$order_id	订单号 / 订单号集
 * @param   string     		$operation	对订单所做的操作
 * @param 	bool			$exit		是否出错停止
 * @return  true / false
 */
function manage_goods_inventory($order_id = 0, $operation = '', $exit = false) {
	if (!$GLOBALS['_CFG']['use_storage'] || !$order_id || !$operation) { return false; }
	if (strpos($order_id, ',') > 0) { $order_id = explode(',', $order_id); }
	$order_ids = array();
	if (is_array($order_id)) { $order_ids = $order_id; }
	else { $order_ids[] = $order_id; }
	/* 初始化数组 */
	$result = array();
	$result['success_sns'] = array();
	$result['error_sns'] = array();
	$result['out_sns'] = array();
	$result['other_sns'] = array();
	/* 数组赋值 */
	foreach($order_ids as $key => $val) {
		$sn = $GLOBALS['db']->getOne("SELECT order_sn FROM " . $GLOBALS['os']->table('order_info') . " WHERE order_id='{$val}'");
		$subresult = manage_good_inventory($val, $operation, $exit);
		if (is_array($subresult)) {
			if ($subresult['code'] == 0) { array_push($result['success_sns'], $sn); }
			elseif ($subresult['code'] == 2) { array_push($result['error_sns'], $sn); }
			elseif ($subresult['code'] == 3) { array_push($result['out_sns'], $sn); }
		} else {
			if ($subresult) { array_push($result['success_sns'], $sn); }
			else { array_push($result['other_sns'], $sn); }
		}
	}
	
	return $result;
}

/**
 * 管理Openshop的单张订单商品库存接口 
 * 
 * @param   int 	$order_id	订单号
 * @param   string  $operation	对订单所做的操作
 * @param 	bool	$exit		是否出错停止
 * @return  true / false
 */
function manage_good_inventory($order_id = 0, $operation = '', $exit = false) {
	if (!$GLOBALS['_CFG']['use_storage'] || !$order_id || !$operation) { return false; }
	$order = order_info($order_id);
	$minus_available_operations = array('order', 'confirm', 'pay', 'range');
	$add_available_operations = array('invalid', 'cancel', 'remove', 'unconfirm', 'unrange', 'unpay', 'return', 'refuse', 'part_reject', 'all_reject');
	$minus_actual_operations = array('ship');
	$add_actual_operations = array('unship', 'remove', 'return', 'refuse', 'part_reject', 'all_reject');
	/* 更新占用现货库存 */
	$when = explode(',', $GLOBALS['_CFG']['when_occupied_stock']);
	foreach($when as $key => $val) {
		if (!$val) { unset($minus_available_operations[$key]); } 
	}
	/* 减可用现货库存 */
	if (in_array($operation, $minus_available_operations) && !$order['occupied_stock']) {
		$result = check_goods_inventory($order['order_id']);
		if ($result['code'] == 0) {
			change_goods_inventory($order['order_id'], true);
		} else {
			if ($exit) { sys_msg($result['msg']); exit; }
			else { return $result; }
		}
	}
	/* 加可用现货库存 */
	if (in_array($operation, $add_available_operations) && $order['occupied_stock']) {
		$allow = 1;
		if ($operation == 'unconfirm') {
			if (in_array('order', $minus_available_operations) || (in_array('pay', $minus_available_operations) && $order['pay_status'] == PS_PAYED)) {
				$allow = 0;
			}
		} elseif ($operation == 'unpay') {
			if (in_array('order', $minus_available_operations) || (in_array('confirm', $minus_available_operations) && $order['order_status'] == OS_CONFIRMED)) {
				$allow = 0;
			}
		} elseif ($operation == 'unrange') {
			if (in_array('order', $minus_available_operations) || (in_array('confirm', $minus_available_operations) && $order['order_status'] == OS_CONFIRMED) || (in_array('pay', $minus_available_operations) && $order['pay_status'] == PS_PAYED)) {
				$allow = 0;
			}
		}
		if ($allow) { change_goods_inventory($order['order_id'], false); }
	}
	/* 减实际库存 */
	if (in_array($operation, $minus_actual_operations)) {
		$result = check_goods_inventory($order['order_id'], 1);
		if ($result['code'] == 0) {
			change_goods_inventory($order['order_id'], true, 1);
		} else {
			if ($exit) { sys_msg($result['msg']); exit; }
			else { return $result; }
		}
	}
	/* 加实际库存 */
	if (in_array($operation, $add_actual_operations)) {
		change_goods_inventory($order['order_id'], false, 1);
	}
	
	return true;
}

/**
 * 检查订单中商品的库存是否足够，返回正常、失败、缺货
 * 
 * @param   int     $order_id   订单号
 * @param   int     $is_ship    如果是下订单的时候则判断可用现货库存
 *                              如果是发货的时候则判断实际库存+预售库存（检查是否开启）-占用库存
 * @return  array
 */
function check_goods_inventory($order_id = 0, $is_ship = 0) {
	$result = array();
	
    /* 查询订单商品信息 */
    $sql = "SELECT o.goods_id,SUM(o.goods_number) AS goods_number,o.color_id,o.size_id FROM " . $GLOBALS['os']->table('order_goods') . " AS o WHERE o.order_id = '$order_id' AND is_real = 1 GROUP BY o.goods_id,o.color_id,o.size_id ";
    $res = $GLOBALS['db']->getAll($sql);	
    
    $out = array();
    $result['code'] = 0;
    $success_exist = 0;
   	
    foreach ($res as $res_goods) {
        $res_goods_id = $res_goods['goods_id'];
        $res_color_id = $res_goods['color_id'];
        $res_size_id  = $res_goods['size_id'];
		$res_goods_number = $res_goods['goods_number'];
		
		//获得商品可用数量
		$goods_number_check = '';
    	if ($is_ship) { //实际库存
    		if ($GLOBALS['_CFG']['use_presale']) { $goods_number_field = "goods_number_actual+goods_number_presale"; }
    		else { $goods_number_field = "goods_number_actual"; }
    		$goods_number_check = $GLOBALS['db']->getOne("SELECT $goods_number_field FROM " . 
    			$GLOBALS['os']->table('goods_inventory') . " WHERE goods_id = '" . $res_goods_id . 
    			"' and color_id = '" . $res_color_id . "' and size_id = '" . $res_size_id . "'");
    	} else {
    		$goods_number_check = $GLOBALS['db']->getOne("SELECT goods_number_available FROM " . 
    			$GLOBALS['os']->table('goods_inventory') . " WHERE goods_id = '" . $res_goods_id . 
    			"' and color_id = '" . $res_color_id . "' and size_id = '" . $res_size_id . "'");
    	}
    	
    	//检验可用数量是否足够
    	if ($goods_number_check < $res_goods_number) {
    		$out_num = intval($res_goods_number - $goods_number_check);
    		$res_goods_name = $GLOBALS['db']->getOne("SELECT goods_name FROM " . $GLOBALS['os']->table('goods') . 
    			" WHERE goods_id='{$res_goods_id}'");
    		$res_color_name = $GLOBALS['db']->getOne("SELECT color_name FROM " . $GLOBALS['os']->table('color') . 
    			" WHERE color_id='{$res_color_id}'");
    		$res_size_name = $GLOBALS['db']->getOne("SELECT size_name FROM " . $GLOBALS['os']->table('size') . 
    			" WHERE size_id='{$res_size_id}'");
    		$out[$res_goods_id]['goods_name'] = $res_goods_name;
    		$out[$res_goods_id]['color_name'] = $res_color_name;
    		$out[$res_goods_id]['size_name'] = $res_size_name;
    		$out[$res_goods_id]['out_num'] = 0;
    		$out[$res_goods_id]['out_num'] += $out_num;
    		$result['code'] = $success_exist ? ORS_OUT : ORS_ERROR;
    	} else {
    		$success_exist = 1;
    		if ($result['code'] != 0) { $result['code'] = $success_exist ? ORS_OUT : ORS_ERROR; }
    	}
    }
    
    foreach($out as $key => $val) {
    	if(empty($result['msg'])) {
			$result['msg'] = $val['goods_name'] . " &nbsp; 颜色:" . $val['color_name'] . " &nbsp; 尺码:" . $val['size_name'] . " &nbsp; 缺货 " . $val['out_num'] . " 件";
		} else {
			$result['msg'] = "<br />&nbsp;&nbsp;&nbsp;" . $val['goods_name'] . " &nbsp; 颜色:" . $val['color_name'] . " &nbsp; 尺码:" . $val['size_name'] . " &nbsp; 缺货 " . $val['out_num'] . " 件";
		}
    }
    
	return $result;
}

/**
 * 改变订单商品的库存表中可用现货库存、实际库存
 * 
 * @param   int     $order_id   订单号
 * @param   bool    $is_dec     是否减少库存
 * @param   int     $is_ship    如果是下订单的时候减库存则修改可用现货库存
 *                              如果是发货的时候减库存则修改实际库存
 */
function change_goods_inventory($order_id = 0, $is_dec = true, $is_ship = 0, $flag = '') {
    /* 查询订单商品信息 */
    $sql = "SELECT o.goods_id,SUM(o.goods_number) AS goods_number,o.color_id,o.size_id FROM " . $GLOBALS['os']->table('order_goods') .
            " as o WHERE o.order_id = '$order_id' AND is_real = 1 GROUP BY o.goods_id,o.color_id,o.size_id ";
    $res = $GLOBALS['db']->getAll($sql);	
    
    $operate = '+';
    $condition = '';
        
	if ($is_dec) {
		$operate = '-';	
	}
    
    foreach ($res as $res_goods) {
        $res_goods_id = $res_goods['goods_id'];
        $res_color_id = $res_goods['color_id'];
        $res_size_id  = $res_goods['size_id'];
		$res_goods_number = $res_goods['goods_number'];
		
		if (!$is_ship) {
			$occupied_stock = ($operate == '+') ? 0 : 1;
			$GLOBALS['db']->query("UPDATE " . $GLOBALS['os']->table('order_info') . " SET occupied_stock='{$occupied_stock}' WHERE order_id='{$order_id}'");
			$condition = "goods_number_available = goods_number_available ".$operate." ".$res_goods_number;
		} else {
			$condition = "goods_number_actual = goods_number_actual ".$operate." ".$res_goods_number;        	
    	}
    		
		$sql = "UPDATE " . $GLOBALS['os']->table('goods_inventory') .
               " SET " . $condition . 
               " WHERE goods_id = '" . $res_goods_id . "' and color_id = " . $res_color_id . ' and size_id = ' . $res_size_id;
        $GLOBALS['db']->query($sql);
    }
}

/**
 * 改变商品的库存表中可用现货库存、实际库存
 * 
 * @param   int     $goods_id   	商品ID
 * @param	int		$color_id		颜色ID
 * @param 	int		$size_id		尺码ID
 * @param 	int		$goods_number	修改数量	
 * @param   bool    $is_dec     	是否减少库存
 * @param   int     $is_ship    	修改 可用现货库存 or 实际库存 
 */
function change_good_inventory($goods_id = 0, $color_id = 0, $size_id = 0, $goods_number = 0, $is_dec = true, $is_ship = 0) {
	if (!$goods_id || !$color_id || !$size_id) { return false; }
    
    $operate = '+';
    $condition = ''; 
	if ($is_dec) { $operate = '-'; }
    
	if (!$is_ship) {
		$condition = "goods_number_available = goods_number_available ".$operate." ".intval($goods_number);
	} else {
		$condition = "goods_number_actual = goods_number_actual ".$operate." ".intval(goods_number);        	
	}
	$sql = "UPDATE " . $GLOBALS['os']->table('goods_inventory') .
           " SET " . $condition . 
           " WHERE goods_id = '" . $goods_id . "' and color_id = '" . $color_id . "' and size_id = '" . $size_id . "'";
    $GLOBALS['db']->query($sql);
}

/*------------------------------------------------------ */
//-- 函数库
/*------------------------------------------------------ */

function get_order_lock_status($order_id){
	$sql = 'select lock_status from '.$GLOBALS['os']->table('order_info').' where order_id = '.$order_id;
	return $GLOBALS['db']->getOne($sql);
}

function get_order_return_set($type=0){
	$sql = 'select * from '.$GLOBALS['os']->table('return_set').' where type = '.$type.' order by id asc';
	return  $GLOBALS['db']->getAll($sql);
}

function get_order_return_info($info_id){
	$sql = 'select name from '.$GLOBALS['os']->table('return_set').' where id = '.$info_id;
	return $GLOBALS['db']->getOne($sql);
}

/**
 * 取得状态列表
 * @param   string  $type   类型：all | order | shipping | payment
 */
function get_status_list($type = 'all')
{
	global $_LANG;

	$list = array();

	if ($type == 'all' || $type == 'order')
	{
		$pre = $type == 'all' ? 'os_' : '';
		foreach ($_LANG['os'] AS $key => $value)
		{
			$list[$pre . $key] = $value;
		}
	}

	if ($type == 'all' || $type == 'shipping')
	{
		$pre = $type == 'all' ? 'ss_' : '';
		foreach ($_LANG['ss'] AS $key => $value)
		{
			$list[$pre . $key] = $value;
		}
	}

	if ($type == 'all' || $type == 'payment')
	{
		$pre = $type == 'all' ? 'ps_' : '';
		foreach ($_LANG['ps'] AS $key => $value)
		{
			$list[$pre . $key] = $value;
		}
	}
	return $list;
}

/**
 * 退回余额、积分、红包（取消、无效、退货时），把订单使用余额、积分、红包设为0
 * @param   array   $order  订单信息
 */
function return_user_surplus_integral_bonus($order_return)
{
	/* 处理余额、积分、红包 */
	if ($order_return['user_id'] > 0 && $order_return['surplus'] > 0)
	{

		$sql = 'select return_total_fee from '. $GLOBALS['os']->table('order_return') . ' where relating_order_sn = '.$order_return['order_sn'];
		$surplus = $GLOBALS['db']->getOne($sql);
		
		if($surplus == 0){
			$surplus = $order_return['money_paid'] < 0 ? $order_return['surplus'] + $order_return['money_paid'] : $order_return['surplus'];
		}

		log_account_change($order_return['user_id'], $surplus, 0, 0, 0, sprintf('由于取消、无效或退货操作，退回支付订单 %s 时使用的预付款', $order_return['order_sn']));
		$GLOBALS['db']->query("UPDATE ". $GLOBALS['os']->table('order_info') . " SET `order_amount` = '0' WHERE `order_id` =". $order_return['order_id']);
	}

	if ($order_return['user_id'] > 0 && $order_return['integral'] > 0)
	{
		log_account_change($order_return['user_id'], 0, 0, 0, $order_return['integral'], sprintf('由于取消、无效或退货操作，退回支付订单 %s 时使用的积分', $order_return['order_sn']));
	}

	if ($order_return['bonus_id'] > 0)
	{
		unuse_bonus($order_return['bonus_id']);
	}

	/* 修改订单 */
	$arr = array(
	'bonus_id'  => 0,
	'bonus'     => 0,
	'integral'  => 0,
	'integral_money'    => 0,
	'surplus'   => 0
	);
	update_order($order_return['order_id'], $arr);
}

/**
 * 更新订单总金额
 * @param   int     $order_id   订单id
 * @return  bool
 */
function update_order_amount($order_id)
{
	include_once(ROOT_PATH . 'includes/lib_order.php');
	//更新订单总金额
	$sql = "UPDATE " . $GLOBALS['os']->table('order_info') .
	" SET order_amount = " . order_due_field() .
	" WHERE order_id = '$order_id' LIMIT 1";

	return $GLOBALS['db']->query($sql);
}

function get_order_discount_rate_byid($order_id)
{
	$sql = 'select (goods_amount+tax+shipping_fee+pay_fee+pack_fee+card_fee) as total_fee from '.$GLOBALS['os']->table('order_info').' as i where i.order_id = '.$order_id;
	$total_fee = $GLOBALS['db']->getOne($sql);
	
	$sql = 'select (goods_amount+tax+shipping_fee+pay_fee+pack_fee+card_fee-bonus-discount) as pay_fee from '.$GLOBALS['os']->table('order_info').' as i where i.order_id = '.$order_id;
	$pay_fee = $GLOBALS['db']->getOne($sql);
	
	return round(floatval($pay_fee/$total_fee),4);
}

function get_order_discount_rate_bysn($order_sn)
{
	$sql = 'select (goods_amount+tax+shipping_fee+pay_fee+pack_fee+card_fee) as total_fee from '.$GLOBALS['os']->table('order_info').' as i where i.order_sn = '.$order_sn;
	$total_fee = $GLOBALS['db']->getOne($sql);
	
	$sql = 'select (goods_amount+tax+shipping_fee+pay_fee+pack_fee+card_fee-bonus-discount) as pay_fee from '.$GLOBALS['os']->table('order_info').' as i where i.order_sn = '.$order_sn;
	$pay_fee = $GLOBALS['db']->getOne($sql);
	
	return round(floatval($pay_fee/$total_fee),4);
}

/**
 * 退货单相关操作
 *
 * @param $array $action_code
 */
function operable_return_list($action_code){

	$list = array();

	if(in_array('all',$action_code)){

		$list['save']    			= true;
		$list['confirm']			= true;
		$list['unconfirm']    		= true;
		$list['pass']     			= true;
		$list['unpass']	    		= true;
		$list['invalid'] 			= true;
		$list['finish'] 			= true;

	}

	if(in_array('return_save',$action_code)){
		$list['save']       = true;
	}
	if (in_array('return_confirm',$action_code)){
		$list['confirm']	= true;
	}
	if (in_array('return_unconfirm',$action_code)){
		$list['unconfirm']  = true;
	}
	if (in_array('return_pass',$action_code)){
		$list['pass']       = true;
	}
	if (in_array('return_unpass',$action_code)){
		$list['unpass']     = true;
	}
	if (in_array('return_invalid',$action_code)){
		$list['invalid']    = true;
	}
	if (in_array('return_finish',$action_code)){
		$list['finish']     = true;
	}

	return $list;
}

/**
 * 返回某个订单可执行的操作列表，包括权限判断
 *
 * @param   array   $order      订单信息 order_status, shipping_status, pay_status
 * @param   bool    $is_cod     支付方式是否货到付款
 * @return  array   可执行的操作
 */
function operable_list($order,$action_code)
{

	$invoice_print = $order['invoice_status'];
	/* 根据状态返回可执行操作 */
	$list = array();
	if(in_array('all',$action_code)){

		$list['confirm']    			= true;
		$list['unconfirm']    			= true;
		$list['range']					= true;
		$list['unrange']				= true;
		$list['invalid']    			= true;
		$list['cancel']     			= true;
		$list['lock']	    			= true;
		$list['unlock'] 				= true;

		$list['pay'] 					= true;
		$list['unpay'] 					= true;
		$list['pay_finish'] 			= true;

		$list['print'] = true;
		$list['invoice_print'] = true;
		$list['ship_print'] = true;
		$list['ship'] = true;
		$list['unship'] = true;
		$list['chase'] = true;

		$list['edit_fee'] = true;
		$list['edit_goods'] = true;
		$list['edit_consignee'] = true;
		$list['edit_other'] = true;
		$list['edit_ship'] = true;
		$list['edit_delivery'] = true;
		$list['edit_pay'] = true;

		$list['returned'] = true;
		$list['remove'] = true;
		
		$list['split']    = true;
		$list['suspend']  = true;
		$list['rollback']    = true;
		$list['remove_suspend'] = true;
		$list['question'] = true;
		$list['remove_question'] = true;
		
		$list['out_handle'] = true;	
		
	}
	if (in_array('order_confirm',$action_code)){
		$list['confirm']    = true;
	}
	if (in_array('order_unconfirm',$action_code)){
		$list['unconfirm']    = true;
	}
	if (in_array('order_confirm',$action_code)){
		$list['range']    = true;
	}
	if (in_array('order_unconfirm',$action_code)){
		$list['unrange']    = true;
	}
	if (in_array('order_cancel',$action_code)){
		$list['cancel']    = true;
	}
	if (in_array('order_invalid',$action_code)){
		$list['invalid']    = true;
	}
	if (in_array('order_lock',$action_code)){
		$list['lock']    = true;
	}
	if (in_array('order_unlock',$action_code)){
		$list['unlock']    = true;
	}
	if (in_array('order_pay',$action_code)){
		$list['pay']    = true;
	}
	if (in_array('order_unpay',$action_code)){
		$list['unpay']    = true;
	}
	if (in_array('order_pay_finish',$action_code)){
		$list['pay_finish']    = true;
	}
	if (in_array('order_invoice_print',$action_code)){
		$list['invoice_print']    = true;
	}
	if (in_array('order_print',$action_code)){
		$list['print']    = true;
	}
	if (in_array('order_ship_print',$action_code)){
		$list['ship_print']    = true;
	}
	if (in_array('order_ship',$action_code)){
		$list['ship']    = true;
	}
	if (in_array('order_ship',$action_code)){
		$list['unship']    = true;
	}
	if (in_array('order_ship',$action_code)){
		$list['chase']    = true;
	}
	if (in_array('order_edit_pay',$action_code)){
		$list['edit_pay']    = true;
	}
	if (in_array('order_edit_delivery',$action_code)){
		$list['edit_delivery']    = true;
	}
	if (in_array('order_edit_ship',$action_code)){
		$list['edit_ship']    = true;
	}
	if (in_array('order_edit_other',$action_code)){
		$list['edit_other']    = true;
	}
	if (in_array('order_edit_consignee',$action_code)){
		$list['edit_consignee']    = true;
	}
	if (in_array('order_edit_goods',$action_code)){
		$list['edit_goods']    = true;
	}
	if (in_array('order_edit_fee',$action_code)){
		$list['edit_fee']    = true;
	}
	if (in_array('order_returned',$action_code)){
		$list['returned']    = true;
	}
	if (in_array('order_remove',$action_code)){
		$list['remove']    = true;
	}
	if (in_array('order_suspend',$action_code)){
		$list['suspend']    = true;
	}
	if (in_array('order_remove_suspend',$action_code)){
		$list['remove_suspend']    = true;
	}
	if (in_array('order_question',$action_code)){
		$list['question']    = true;
	}
	if (in_array('order_remove_question',$action_code)){
		$list['remove_question']    = true;
	}
	if (in_array('order_split',$action_code)){
		$list['split']    = true;
	}
	if (in_array('order_rollback',$action_code)){
		$list['rollback']    = true;
	}
	if (in_array('out_handle',$action_code)){
		$list['out_handle']    = true;
	}
	
	/*根据订单状态，调整可操作性*/
	if($order['shipping_status'] == SS_SHIPPED){
		$list['edit_fee'] = false;
		$list['edit_goods'] = false;
		$list['edit_consignee'] = false;
		$list['edit_other'] = false;
		$list['edit_ship'] = false;
		$list['edit_delivery'] = false;
		$list['edit_pay'] = false;
	}
	/* 修正发货操作 */
	if (!empty($list['ship']))
	{
		/* 如果是团购活动且未处理成功，不能发货 */
		if ($order['extension_code'] == 'group_buy')
		{
			include_once(ROOT_PATH . 'includes/lib_goods.php');
			$group_buy = group_buy_info(intval($order['extension_id']));
			if ($group_buy['status'] != GBS_SUCCEED)
			{
				unset($list['ship']);
			}
		}
	}

	return $list;
}

function update_order_lock_status($order_id,$value = 0)
{
	$sql = 'UPDATE '.$GLOBALS['os']->table('order_info').' SET lock_status = '.$value.' WHERE order_id = '.$order_id;
	$GLOBALS['db']->query($sql);
}

/**
 * 根据当前session中action_list内放置的ID列表,查询相应的action_name
 * @return array 返回当前系统登陆管理员可操作权限的action_code列表
 */
function get_action_name_list(){

	$action_list = $_SESSION['action_list'];
	$action_name_list = '';
	if($action_list == 'all'){
		$action_name_list = 'all';
	}else{
		$sql = 'select a.action_code,a.action_name from '.$GLOBALS['os']->table('acl_action').' as a where a.action_id in ('.$action_list.')';
		$action_name_list = $GLOBALS['db']->getAll($sql);
	}
	return $action_name_list;
}

/**
 * @return int 返回当前系统登陆管理员的具体角色
 */
function get_current_role($role_action){

	global $ARR_ADMIN_CALLCENTER;
	global $ARR_ADMIN_FINANCE;
	global $ARR_ADMIN_WAREHOUSE;

	$role = ADMIN_GLOBAL;

	if(role_judge($ARR_ADMIN_CALLCENTER, $role_action)){
		$role = ADMIN_CALLCENTER;
	}elseif(role_judge($ARR_ADMIN_FINANCE, $role_action)){
		$role = ADMIN_FINANCE;
	}elseif(role_judge($ARR_ADMIN_WAREHOUSE, $role_action)){
		$role = ADMIN_WAREHOUSE;
	}

	return $role;
}

function role_judge($role_arr,$role_action){
	$i = 0;
	foreach ($role_arr as $key => $value) {
		if (in_array($value, $role_action)) {
			$i++;
		}
	}
	return $i == sizeof($role_arr);
}

/**
 * 处理编辑订单时订单金额变动
 * @param   array   $order  订单信息
 * @param   array   $msgs   提示信息
 * @param   array   $links  链接信息
 */
function handle_order_money_change($order, &$msgs, &$links)
{
	$order_id = $order['order_id'];
	if ($order['pay_status'] == PS_PAYED || $order['pay_status'] == PS_PAYING)
	{
		/* 应付款金额 */
		$money_dues = $order['order_amount'];
		if ($money_dues > 0)
		{
			/* 修改订单为未付款 */
			update_order($order_id, array('pay_status' => PS_UNPAYED, 'pay_time' => 0));
			$msgs[]     = '由于您修改了订单，导致订单总金额增加，需要再次付款';
			$links[]    = array('text' => '订单信息', 'href' => 'order.php?act=info&order_id=' . $order_id);
		}
		elseif ($money_dues < 0)
		{
			$anonymous  = $order['user_id'] > 0 ? 0 : 1;
			$msgs[]     = '由于您修改了订单，导致订单总金额减少，需要退款';
			$links[]    = array('text' => '退款', 'href' => 'order.php?act=process&func=load_refund&anonymous=' .
			$anonymous . '&order_id=' . $order_id . '&refund_amount=' . abs($money_dues));
		}
	}
}

function order_return_list($return_type='1',$arr='',$brr='')
{
	$module_array = array('1' => 'order_return_list', '2' => 'order_refuse_list');
	$result = get_filter();
	if ($result === false)
	{
		$where = 'WHERE 1 ';
		
		if(intval($return_type))
		{
			$where .= " and return_type='{$return_type}' ";  //设置搜索条件： 正常退单 or 拒收入库
		}
		
		$filter['module'] = $module_array[$return_type];
		
		/* 正常退单搜索条件 */
		if($arr != '' && !empty($arr)){
			$filter['return_sn'] = $arr['return_sn'];
			$filter['return_consignee'] = $arr['return_consignee'];
			$filter['status'] = $arr['status'];
		}
		if ($filter['return_sn'])
		{
			$where .= " AND o.return_sn LIKE '%" . mysql_like_quote($filter['return_sn']) . "%'";
		}
		if ($filter['return_consignee'])
		{
			$where .= " AND o.return_consignee LIKE '%" . mysql_like_quote($filter['return_consignee']) . "%'";
		}		
		if ($filter['status'] > 0)
		{
			$where .= " AND o.return_order_status  = '$filter[status]'";
		}
		
		/* 拒收入库搜索条件 */
		if($brr != '' && !empty($brr)){
			$filter['refuse_sn'] = $brr['refuse_sn'];
			$filter['refuse_consignee'] = $brr['refuse_consignee'];
			$filter['status'] = $brr['status'];
		}
		if ($filter['refuse_sn'])
		{
			$where .= " AND o.return_sn LIKE '%" . mysql_like_quote($filter['refuse_sn']) . "%'";
		}
		if ($filter['refuse_consignee'])
		{
			$where .= " AND o.return_consignee LIKE '%" . mysql_like_quote($filter['refuse_consignee']) . "%'";
		}		
		if ($filter['status'] > 0)
		{
			$where .= " AND o.return_order_status = '" . $filter['status'] . "'";
		}	
		
		/* 公用排序方式 */
		$filter['sort_by'] = empty($_REQUEST['sort_by']) ? 'add_time' : trim($_REQUEST['sort_by']);
		$filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

		/* 分页大小 */
		$filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);

		if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
		{
			$filter['page_size'] = intval($_REQUEST['page_size']);
		}
		elseif (isset($_COOKIE['OSCP']['page_size']) && intval($_COOKIE['OSCP']['page_size']) > 0)
		{
			$filter['page_size'] = intval($_COOKIE['OSCP']['page_size']);
		}
		else
		{
			$filter['page_size'] = 20;
		}
		
		/* 记录总数 */
		if ($filter['user_name'])
		{
			$sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('order_return') . " AS o ,".
			$GLOBALS['os']->table('users') . " AS u " . $where;
		}
		else
		{
			$sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('order_return') . " AS o ". $where;
		}
		
		$filter['record_count']   = $GLOBALS['db']->getOne($sql);
		$filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;

		/* 查询 */
		$sql =  " SELECT * FROM " . $GLOBALS['os']->table('order_return') . " AS o " . $where .
		" ORDER BY $filter[sort_by] $filter[sort_order] ".
		" LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ",$filter[page_size]";

		foreach (array('order_sn', 'consignee', 'email', 'address', 'zipcode', 'tel', 'user_name') AS $val)
		{
			$filter[$val] = stripslashes($filter[$val]);
		}
		set_filter($filter, $sql);
	}
	else
	{
		$sql    = $result['sql'];
		$filter = $result['filter'];
	}

	$row = $GLOBALS['db']->getAll($sql);
	/* 格式话数据 */
	foreach ($row AS $key => $value)
	{
		$row[$key]['formated_order_amount'] = price_format($value['order_amount']);
		$row[$key]['formated_money_paid'] = price_format($value['money_paid']);
		$row[$key]['formated_total_fee'] = price_format($value['total_fee']);
		$row[$key]['add_time'] = local_date('Y-m-d H:i', $value['add_time']);
		if ($value['return_order_status'] == RS_INVALID)
		{
			/* 如果该退货单为无效则显示删除链接 */
			$row[$key]['can_remove'] = 1;
		}
		else
		{
			$row[$key]['can_remove'] = 0;
		}
	}

	$arr = array('orders_return' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);

	return $arr;
}

function order_suspend_list($arr = '')
{
	$result = get_filter();
	$filter['module'] = 'order_suspend_list';
	
	if ($result === false)
	{
		
		if($arr != '' && !empty($arr)){
			$filter['order_sn'] = $arr['relating_order_sn'];
			$filter['from_reason']  = $arr['from_reason'];
			$filter['process_mode'] = $arr['process_mode'];
			$filter['process_status']  = $arr['process_status'];
			$filter['start_time'] = $arr['start_time'];
			$filter['end_time']  = $arr['end_time'];
		}
		
		if ($filter['order_sn'])
		{
			$where .= " AND s.relating_order_sn LIKE '%".mysql_like_quote($filter['order_sn'])."%'";
		}
		if ($filter['from_reason'])
		{
			$where .= " AND (s.suspend_reason LIKE '%".mysql_like_quote($filter['from_reason'])."%' OR s.from_user LIKE '%".mysql_like_quote($filter['from_reason'])."%')";
		}
		if ($filter['process_mode'] != -1)
		{
			$where .= " AND s.process_mode  = '$filter[process_mode]'";
		}
		if ($filter['process_status'] != -1)
		{
			$where .= " AND s.process_status  = '$filter[process_status]'";
		}		
		if ($filter['start_time'])
		{
			$where .= " AND s.add_time >= '".local_strtotime($filter[start_time])."'";
		}
		if ($filter['end_time'])
		{
			$where .= " AND s.add_time <= '".local_strtotime($filter[end_time])."'";
		}
		
		/* 分页大小 */
		$filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);
		
		if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
		{
			$filter['page_size'] = intval($_REQUEST['page_size']);
		}
		elseif (isset($_COOKIE['OSCP']['page_size']) && intval($_COOKIE['OSCP']['page_size']) > 0)
		{
			$filter['page_size'] = intval($_COOKIE['OSCP']['page_size']);
		}
		else
		{
			$filter['page_size'] = 20;
		}
		/* 记录总数 */

		$sql = "SELECT COUNT(s.id) FROM " . $GLOBALS['os']->table('order_suspend') . " AS s, " . $GLOBALS['os']->table('order_info') . " AS oi WHERE s.relating_order_id=oi.order_id " . $where;
		
		$filter['record_count']   = $GLOBALS['db']->getOne($sql);
		$filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;		
		/* 查询 */
		$sql = "SELECT s.id, s.relating_order_id, s.relating_order_sn, s.suspend_reason, s.add_time AS suspend_time, s.end_time, s.process_status AS suspend_status, oi.*, (" . order_amount_field('oi.') . ") AS total_fee " .
		" FROM " . $GLOBALS['os']->table('order_suspend') . " AS s, " . $GLOBALS['os']->table('order_info') . " AS oi WHERE s.relating_order_id=oi.order_id " . $where .
		" ORDER BY s.id desc " .
		" LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ",$filter[page_size]";
		
	}else{
		$sql    = $result['sql'];
		$filter = $result['filter'];
	}

	$row = $GLOBALS['db']->getAll($sql);
	
	foreach ($row AS $key => $value)
	{
		$row[$key]['suspend_time'] = local_date('Y-m-d H:i', $value['suspend_time']);
		$row[$key]['end_time']     = local_date('Y-m-d H:i', $value['end_time']);
		$row[$key]['formated_order_amount'] = price_format($value['order_amount']);
		$row[$key]['formated_money_paid'] = price_format($value['money_paid']);
		$row[$key]['formated_total_fee'] = price_format($value['total_fee']);
	}

	$arr = array('order_suspend_list' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);

	return $arr;
}

function order_out_list($arr = '')
{
	$result = get_filter();
	$filter['module'] = 'order_out_list';
	
	if ($result === false)
	{
		if($arr != '' && !empty($arr)){
			$filter['order_sn'] = $arr['relating_order_sn'];
			$filter['process_mode'] = $arr['process_mode'];
			$filter['process_status']  = $arr['process_status'];
		}
		
		$where = 'WHERE o.user_id > 0 ';
	
		if ($filter['order_sn'])
		{
			$where .= " AND s.relating_order_sn LIKE '%".mysql_like_quote($filter['order_sn'])."%'";
		}
		if ($filter['process_mode'] != -1)
		{
			$where .= " AND s.process_mode  = '$filter[process_mode]'";
		}
		if ($filter['process_status'] != -1)
		{
			$where .= " AND s.process_status  = '$filter[process_status]'";
		}
		
		/* 分页大小 */
		$filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);
		
		if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
		{
			$filter['page_size'] = intval($_REQUEST['page_size']);
		}
		elseif (isset($_COOKIE['OSCP']['page_size']) && intval($_COOKIE['OSCP']['page_size']) > 0)
		{
			$filter['page_size'] = intval($_COOKIE['OSCP']['page_size']);
		}
		else
		{
			$filter['page_size'] = 20;
		}
		/* 记录总数 */

		$sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('order_out') . " AS s LEFT JOIN " . $GLOBALS['os']->table('order_info') . " AS o ON s.relating_order_sn=o.order_sn " . $where;
		
		$filter['record_count']   = $GLOBALS['db']->getOne($sql);
		$filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;		
		/* 查询 */
		$sql = "SELECT s.*, o.order_id, o.postscript, o.to_buyer ".
		" FROM " . $GLOBALS['os']->table('order_out') . " AS s LEFT JOIN " . $GLOBALS['os']->table('order_info') . " AS o ON s.relating_order_sn = o.order_sn " .$where.
		" ORDER BY id DESC ".
		" LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ",$filter[page_size]";
		
	}else{
		$sql    = $result['sql'];
		$filter = $result['filter'];
	}

	$row = $GLOBALS['db']->getAll($sql);

	foreach ($row AS $key => $value)
	{
		$row[$key]['add_time']   	  = local_date('Y-m-d H:i', $value['add_time']);
		$row[$key]['start_time'] 	  = local_date('Y-m-d H:i', $value['start_time']);
		$row[$key]['end_time']   	  = local_date('Y-m-d H:i', $value['end_time']);
		$row[$key]['substr_to_buyer'] = sub_str($value['to_buyer'], 45);
		$result = check_goods_inventory($value['order_id']);
		if ($result['code'] == 0) { $row[$key]['available'] = '1'; }
		else { $row[$key]['available'] = '0'; }
	}

	$arr = array('order_out_list' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);

	return $arr;
}

function order_question_list($arr = '')
{
	$result = get_filter();
	$filter['module'] = 'order_question_list';
	
	if ($result === false)
	{
		if($arr != '' && !empty($arr)){
			$filter['order_sn'] = $arr['relating_order_sn'];
			$filter['question_reason'] = $arr['question_reason'];
		}
		
		if ($filter['order_sn'])
		{
			$where .= " AND s.relating_order_sn LIKE '%".mysql_like_quote($filter['order_sn'])."%'";
		}
		if ($filter['question_reason'])
		{
			$where .= " AND s.question_reason LIKE '%".mysql_like_quote($filter['question_reason'])."%'";
		}
		
		/* 分页大小 */
		$filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);
		
		if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
		{
			$filter['page_size'] = intval($_REQUEST['page_size']);
		}
		elseif (isset($_COOKIE['OSCP']['page_size']) && intval($_COOKIE['OSCP']['page_size']) > 0)
		{
			$filter['page_size'] = intval($_COOKIE['OSCP']['page_size']);
		}
		else
		{
			$filter['page_size'] = 20;
		}
		/* 记录总数 */

		$sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('order_question') . " AS s, " . $GLOBALS['os']->table('order_info') . " AS oi WHERE s.relating_order_sn=oi.order_sn AND oi.user_id>'0' " . $where;
		
		$filter['record_count']   = $GLOBALS['db']->getOne($sql);
		$filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;		
		/* 查询 */
		$sql = "SELECT s.id, s.relating_order_id, s.relating_order_sn, s.question_reason, s.add_time AS question_time, s.end_time, s.process_status AS question_status, oi.*, (" . order_amount_field('oi.') . ") AS total_fee " .
		" FROM " . $GLOBALS['os']->table('order_question') . " AS s, " . $GLOBALS['os']->table('order_info') . " AS oi WHERE s.relating_order_id=oi.order_id " . $where .
		" ORDER BY s.id desc " .
		" LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ",$filter[page_size]";
		
	}else{
		$sql    = $result['sql'];
		$filter = $result['filter'];
	}

	$row = $GLOBALS['db']->getAll($sql);

	foreach ($row AS $key => $value)
	{
		$row[$key]['question_time']   = local_date('Y-m-d H:i', $value['question_time']);
		$row[$key]['substr_to_buyer'] = sub_str($value['to_buyer'], 45);
		$row[$key]['formated_order_amount'] = price_format($value['order_amount']);
		$row[$key]['formated_money_paid'] = price_format($value['money_paid']);
		$row[$key]['formated_total_fee'] = price_format($value['total_fee']);
	}

	$arr = array('order_question_list' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);

	return $arr;
}

/**
 *  获取订单列表信息
 *
 * @access  public
 * @param
 *
 * @return void
 */
function order_list($type='',$arr = '')
{ 
	$result = get_filter();
	
	$filter['module'] = 'order_list';
	
	if ($result === false)
	{
		if($arr != '' && !empty($arr) && $arr['search_flag'] == 1){
			$filter['search_flag'] = 1;
			$filter['order_sn'] = $arr['order_sn'];
			$filter['consignee'] = $arr['consignee'];
			$filter['composite_status'] = $arr['composite_status'];
			$filter['process_status'] = $arr['process_status'];	
		}else if($arr != '' && !empty($arr) && $type == 'cw_order_list'){
			$filter['order_sn'] = $arr['order_sn'];
			$filter['ship_sn']  = $arr['ship_sn'];
			$filter['shipping_id'] = $arr['shipping_info'];
			$filter['pay_id']  = $arr['pay_info'];		
		}else{
			/* 过滤信息 */
			$filter['shipping_id'] = empty($_REQUEST['shipping_id']) ? 0 : intval($_REQUEST['shipping_id']);		
			$filter['pay_id'] = empty($_REQUEST['pay_id']) ? 0 : intval($_REQUEST['pay_id']);			
			$filter['order_sn'] = empty($_REQUEST['order_sn']) ? '' : trim($_REQUEST['order_sn']);
			$filter['consignee'] = empty($_REQUEST['consignee']) ? '' : trim($_REQUEST['consignee']);		
			$filter['composite_status'] = isset($_REQUEST['composite_status']) ? intval($_REQUEST['composite_status']) : -1;			
		}
		
		if (!empty($_GET['is_ajax']) && $_GET['is_ajax'] == 1)
		{
			$_REQUEST['consignee'] = json_str_iconv($_REQUEST['consignee']);
			//$_REQUEST['address'] = json_str_iconv($_REQUEST['address']);
		}
		
		/* 解决编码问题 */
		$_REQUEST['user_name'] = urldecode($_REQUEST['user_name']);
		$_REQUEST['consignee'] = urldecode($_REQUEST['consignee']);
		
		$filter['goods_sn'] = empty($_REQUEST['goods_sn']) ? '' : trim($_REQUEST['goods_sn']);
		$filter['email'] = empty($_REQUEST['email']) ? '' : trim($_REQUEST['email']);
		$filter['address'] = empty($_REQUEST['address']) ? '' : trim($_REQUEST['address']);
		$filter['zipcode'] = empty($_REQUEST['zipcode']) ? '' : trim($_REQUEST['zipcode']);
		$filter['tel'] = empty($_REQUEST['tel']) ? '' : trim($_REQUEST['tel']);
		$filter['mobile'] = empty($_REQUEST['mobile']) ? 0 : intval($_REQUEST['mobile']);
		$filter['country'] = empty($_REQUEST['country']) ? 0 : intval($_REQUEST['country']);
		$filter['province'] = empty($_REQUEST['province']) ? 0 : intval($_REQUEST['province']);
		$filter['city'] = empty($_REQUEST['city']) ? 0 : intval($_REQUEST['city']);
		$filter['district'] = empty($_REQUEST['district']) ? 0 : intval($_REQUEST['district']);
		$filter['order_status'] = isset($_REQUEST['order_status']) ? intval($_REQUEST['order_status']) : -1;
		$filter['shipping_status'] = isset($_REQUEST['shipping_status']) ? intval($_REQUEST['shipping_status']) : -1;
		$filter['pay_status'] = isset($_REQUEST['pay_status']) ? intval($_REQUEST['pay_status']) : -1;
		$filter['user_id'] = empty($_REQUEST['user_id']) ? 0 : intval($_REQUEST['user_id']);
		$filter['user_name'] = empty($_REQUEST['user_name']) ? '' : trim($_REQUEST['user_name']);
		$filter['consignee'] = empty($_REQUEST['consignee']) ? '' : trim($_REQUEST['consignee']);
		$filter['group_buy_id'] = isset($_REQUEST['group_buy_id']) ? intval($_REQUEST['group_buy_id']) : 0;
		$filter['sort_by'] = empty($_REQUEST['sort_by']) ? 'delivery_time' : trim($_REQUEST['sort_by']);
		$filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'ASC' : trim($_REQUEST['sort_order']);
		$filter['process_status'] = isset($_REQUEST['process_status']) ? intval($_REQUEST['process_status']) : -1;
		$filter['range_status'] = isset($_REQUEST['range_status']) ? intval($_REQUEST['range_status']) : -1;
		
		if( 'shipping_list' == $type ){
			$filter['process_status']=0;
			$filter['ck_jianhuo']=empty($_REQUEST['ck_jianhuo'])?'0':'1';
			$filter['ck_order']=empty($_REQUEST['ck_jianhuo'])?'0':'1';
			$filter['ck_shipping']=empty($_REQUEST['ck_jianhuo'])?'0':'1';
			$filter['sort_order'] = 'ASC';
		}
		if($type == 'kf_order_list'){
			$filter['sort_by'] = 'pay_status';
			$filter['sort_order'] = 'asc';			
		}
		
		/* 解决编码问题 */
		$_REQUEST['start_time'] = urldecode($_REQUEST['start_time']);
		$_REQUEST['end_time'] = urldecode($_REQUEST['end_time']);
		
		$filter['time_type'] = empty($_REQUEST['time_type']) ? 'o.add_time' : 'o.'.trim($_REQUEST['time_type']);
		$filter['start_time'] = empty($_REQUEST['start_time']) ? '' : (strpos($_REQUEST['start_time'], '-') > 0 ?  local_strtotime($_REQUEST['start_time']) : $_REQUEST['start_time']);
		$filter['end_time'] = empty($_REQUEST['end_time']) ? '' : (strpos($_REQUEST['end_time'], '-') > 0 ?  local_strtotime($_REQUEST['end_time']) : $_REQUEST['end_time']);
		
		$filter['delivery_station_id'] = empty($_REQUEST['delivery_station_id']) ? 0 : $_REQUEST['delivery_station_id'];
		
		$where = 'WHERE o.user_id > 0 ';
		if ($filter['order_sn'])
		{
			$where .= " AND o.order_sn LIKE '%" . mysql_like_quote($filter['order_sn']) . "%'";
		}
		
		if ($filter['ship_sn'])
		{
			$where .= " AND o.invoice_no LIKE '%" . mysql_like_quote($filter['ship_sn']) . "%'";
		}		
		if ($filter['consignee'])
		{
			$where .= " AND o.consignee LIKE '%" . mysql_like_quote($filter['consignee']) . "%'";
		}
		if ($filter['email'])
		{
			$where .= " AND o.email LIKE '%" . mysql_like_quote($filter['email']) . "%'";
		}
		if ($filter['address'])
		{
			$where .= " AND o.address LIKE '%" . mysql_like_quote($filter['address']) . "%'";
		}
		if ($filter['zipcode'])
		{
			$where .= " AND o.zipcode LIKE '%" . mysql_like_quote($filter['zipcode']) . "%'";
		}
		if ($filter['tel'])
		{
			$where .= " AND o.tel LIKE '%" . mysql_like_quote($filter['tel']) . "%'";
		}
		if ($filter['mobile'])
		{
			$where .= " AND o.mobile LIKE '%" .mysql_like_quote($filter['mobile']) . "%'";
		}
		if ($filter['country'])
		{
			$where .= " AND o.country = '$filter[country]'";
		}
		if ($filter['province'])
		{
			$where .= " AND o.province = '$filter[province]'";
		}
		if ($filter['city'])
		{
			$where .= " AND o.city = '$filter[city]'";
		}
		if ($filter['district'])
		{
			$where .= " AND o.district = '$filter[district]'";
		}
		if ($filter['shipping_id'] > 0)
		{
			$where .= " AND o.shipping_id  = '$filter[shipping_id]'";
		}
		if ($filter['pay_id'] > 0)
		{
			$where .= " AND o.pay_id  = '$filter[pay_id]'";
		}
		if ($filter['order_status'] != -1)
		{
			$where .= " AND o.order_status  = '$filter[order_status]'";
		}
		if ($filter['shipping_status'] != -1)
		{
			$where .= " AND o.shipping_status = '$filter[shipping_status]'";
		}
		if ($filter['pay_status'] != -1)
		{
			$where .= " AND o.pay_status = '$filter[pay_status]'";
		}
		if ($filter['user_id'])
		{
			$where .= " AND o.user_id = '$filter[user_id]'";
		}
		if ($filter['user_name'])
		{
			$where .= " AND u.user_name LIKE '%" . mysql_like_quote($filter['user_name']) . "%'";
		}
		if ($filter['start_time'])
		{
			$where .= " AND " . $filter['time_type'] . " >= '$filter[start_time]'";
		}
		if ($filter['end_time'])
		{
			$where .= " AND " . $filter['time_type'] . " <= '$filter[end_time]'";
		}
		if ($filter['delivery_station_id'] != -1)
		{
			$where .= " AND o.delivery_station_id = ".$filter[delivery_station_id];
		}
		if ($filter['process_status'] != -1)
		{
			$where .= " AND o.process_status = ".$filter[process_status];
		}
		if ($filter['range_status'] != -1)
		{
			$where .= " AND o.range_status = ".$filter[range_status];
		}
		$sql = 'select pay_id from '.$GLOBALS['os']->table('payment')." WHERE is_cod = 1 ";
		$is_code = $GLOBALS['db']->getOne($sql);

		$sql = 'select pay_code from '.$GLOBALS['os']->table('payment')." WHERE is_online = 1 ";
		$is_online = $GLOBALS['db']->getOne($sql);
		
		if( 'shipping_list' == $type ){
			$filter['module'] = 'shipping_list';
			
			//打印标志位  拣货单 ，订单，物流单
			$filter['ck_jianhuo']=empty($_REQUEST['ck_jianhuo'])?'0':'1';
			$filter['ck_order']=empty($_REQUEST['ck_order'])?'0':'1';
			$filter['ck_shipping']=empty($_REQUEST['ck_shipping'])?'0':'1';
			if(($filter['ck_jianhuo']=='1')){
				$where .= " AND o.invoice_status = 0 ";
			}
			//待发货列表配置选项
			if ($GLOBALS['_CFG']['in_ship_options'] == 0) {
				$status_str = " o.order_status = '" . OS_CONFIRMED . "' ";
			} elseif ($GLOBALS['_CFG']['in_ship_options'] == 1) {
				$status_str = " o.pay_status = '" . PS_PAYED . "' AND o.order_status = '" . OS_UNCONFIRMED . "' ";
			} elseif ($GLOBALS['_CFG']['in_ship_options'] == 2) {
				$status_str = " o.order_status = '" . OS_CONFIRMED . "' OR ( o.pay_status = '" . PS_PAYED . "' AND o.order_status = '" . OS_UNCONFIRMED . "' ) ";
			} elseif ($GLOBALS['_CFG']['in_ship_options'] == 3) {
				$status_str = " o.order_status = '" . OS_CONFIRMED . "' AND ( o.pay_status = '" . PS_PAYED . "' AND o.order_status = '" . OS_UNCONFIRMED . "' ) ";
			} elseif ($GLOBALS['_CFG']['in_ship_options'] == 4 && $GLOBALS['_CFG']['use_ors']) {
				$status_str = " o.order_status = '" . OS_CONFIRMED . "' AND o.range_status = '" . ORS_CONFIRMED . "' ";
			} else {
				if ($GLOBALS['_CFG']['use_ors']) { $status_str = " o.range_status = '" . ORS_CONFIRMED . "' "; }
				else { $status_str = " o.order_status = '" . OS_CONFIRMED . "' OR ( o.pay_status = '" . PS_PAYED . "' AND o.order_status = '" . OS_UNCONFIRMED . "' ) "; }
			}
			$where .= " AND o.shipping_status = ".SS_UNSHIPPED." AND ( ( $status_str ) OR ( o.pay_status = ".PS_UNPAYED." AND o.pay_id = ".$is_code." ) )";
			
			if($arr != '' && !empty($arr) && $arr['search_flag'] == 2){
				$filter['search_flag'] = 2;
				if($arr['shipping_info'] > 0 ){
					$where .= " AND o.shipping_id = ".$arr['shipping_info'];
					$filter['shipping_id'] = $arr['shipping_info'];
				}
				
				if($arr['time_start'] != '' && $arr['time_end'] != ''){
					$time_start = intval(strtotime($arr['time_start'])) - 8*60*60;
					$time_end   = intval(strtotime($arr['time_end'])) - 8*60*60;
					$where .= " AND add_time > ".$time_start." AND add_time < ".$time_end;
					$filter['time_start'] = $arr['time_start'];
					$filter['time_end'] = $arr['time_end'];
				}
			}
			
		}
		
		else if('weigh' == $type){
			$filter['module'] = 'weigh';
			$where .= ' AND o.order_status != '.OS_CANCELED.' AND o.order_status != '.OS_INVALID.' AND o.order_status != '.OS_FINISH.' AND o.order_status != '.OS_MERGED.' AND o.order_status != '.OS_SPLITED.' AND o.shipping_status = '.SS_SHIPPED.' ';
		}

		else if('cw_order_list' == $type){
			$filter['module'] = 'cw_order_list';
			$where .= ' AND o.order_status != '.OS_CANCELED.' AND o.order_status != '.OS_INVALID;
			
			if($arr['cw_status'] == 'to_pay'){
				$where .= " AND (((o.order_status = ".OS_CONFIRMED." and o.shipping_status = ".SS_SHIPPED." and o.pay_id = ".$is_code.") OR (o.pay_id in (select pay_id from ".$GLOBALS['os']->table('payment')." WHERE is_online = 0 and is_cod = 0))) AND o.pay_status = ".PS_UNPAYED.")";	
			}elseif ($arr['cw_status'] == 'to_finish'){
				$where .= " AND o.order_status = ".OS_CONFIRMED." AND o.pay_status = ".PS_PAYED." AND o.shipping_status = ".SS_SHIPPED;
			}else{
				$where .= " AND (((o.order_status = ".OS_CONFIRMED." and o.shipping_status = ".SS_SHIPPED." and o.pay_id = ".$is_code.") OR (o.pay_id in (select pay_id from ".$GLOBALS['os']->table('payment')." WHERE is_online = 0 and is_cod = 0))) AND o.pay_status = ".PS_UNPAYED.") OR (o.order_status = ".OS_CONFIRMED." AND o.pay_status = ".PS_PAYED." AND o.shipping_status = ".SS_SHIPPED.")";
			}
			
			if($arr['start_time'] != '' && $arr['end_time'] != ''){
				$time_start = intval(strtotime($arr['start_time'])) - 8*60*60;
				$time_end   = intval(strtotime($arr['end_time'])) - 8*60*60;
				$where .= " AND add_time > ".$time_start." AND add_time < ".$time_end;
				$filter['start_time']  = $arr['start_time'];
				$filter['end_time'] = $arr['end_time'] ;
			}
			
		}else if('kf_order_list' == $type){
			$filter['module'] = 'kf_order_list';
			$where .= " AND ( o.order_status = ".OS_UNCONFIRMED." AND ( o.lock_status = 0 OR o.lock_status = ".$_SESSION[admin_id]."))";
			
		}else if('order_merge' == $type){
			$filter['module'] = 'order_merge';
			$where .= " AND ( o.order_status = ".OS_UNCONFIRMED." OR o.order_status = ".OS_CONFIRMED." ) AND ( o.pay_status = ".PS_UNPAYED." OR o.pay_status = ".PS_PAYED." ) AND ( o.shipping_status = ".SS_UNSHIPPED." )";
			
		}else if('torange_list' == $type){
			$filter['module'] = 'torange_list';
			//待配货列表配置选项
			if ($GLOBALS['_CFG']['in_range_options'] == 0) {
				$status_str = " o.order_status = '" . OS_CONFIRMED . "' ";
			} elseif ($GLOBALS['_CFG']['in_range_options'] == 1) {
				$status_str = " o.order_status = '" . OS_CONFIRMED . "' AND o.pay_status = '" . PS_PAYED . "' ";
			} elseif ($GLOBALS['_CFG']['in_range_options'] == 2) {
				$status_str = " o.order_status = '" . OS_CONFIRMED . "' OR ( o.order_status = '" . OS_UNCONFIRMED . "' AND o.pay_status = '" . PS_PAYED . "' ) ";
			} elseif ($GLOBALS['_CFG']['in_range_options'] == 3) {
				$status_str = " o.order_status = '" . OS_CONFIRMED . "' AND ( o.order_status = '" . OS_UNCONFIRMED . "' AND o.pay_status = '" . PS_PAYED . "' ) ";
			} else {
				$status_str = " o.order_status = '" . OS_CONFIRMED . "' OR ( o.order_status = '" . OS_UNCONFIRMED . "' AND o.pay_status = '" . PS_PAYED . "' ) ";
			}
			$where .= " AND o.user_id>'0' AND ( $status_str ) AND o.shipping_status = ".SS_UNSHIPPED." AND o.range_status = ".ORS_UNCONFIRMED." ";
			//自动配货X小时以前的所有订单
			if ($arr['time_end'] != '') {
				$where .= " AND o.add_time < '" . $arr['time_end'] . "' ";
			}
		}
		
		if(isset($filter['composite_status'])){
			//综合状态
			switch($filter['composite_status'])
			{
				case CS_AWAIT_PAY :
					$where .= order_query_sql('await_pay');
					break;

				case CS_AWAIT_SHIP :
					$where .= order_query_sql('await_ship');
					break;

				case CS_FINISHED :
					$where .= order_query_sql('finished');
					break;

				case PS_PAYING :
					if ($filter['composite_status'] != -1 && $filter['order_status'] < 0)
					{
						$where .= " AND o.pay_status = '$filter[composite_status]' ";
					}
					break;

				default:
					if ($filter['composite_status'] != -1)
					{
						$where .= " AND o.order_status = '$filter[composite_status]' ";
					}
			}
		}	
		/* 团购订单 */
		if ($filter['group_buy_id'])
		{
			$where .= " AND o.extension_code = 'group_buy' AND o.extension_id = '$filter[group_buy_id]' ";
		}
		
		/* 如果管理员属于某个办事处，只列出这个办事处管辖的订单 */
		$sql = "SELECT agency_id FROM " . $GLOBALS['os']->table('admin_user') . " WHERE user_id = '$_SESSION[admin_id]'";
		$agency_id = $GLOBALS['db']->getOne($sql);
		if ($agency_id > 0)
		{
			$where .= " AND o.agency_id = '$agency_id' ";
		}

		/* 分页大小 */
		$filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);

		if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
		{
			$filter['page_size'] = intval($_REQUEST['page_size']);
		}
		elseif (isset($_COOKIE['OSCP']['page_size']) && intval($_COOKIE['OSCP']['page_size']) > 0)
		{
			$filter['page_size'] = intval($_COOKIE['OSCP']['page_size']);
		}
		else
		{
			$filter['page_size'] = 15;
		}
		
		/* 记录总数 */
		if ($filter['user_name'])
		{
			$sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('order_info') . " AS o LEFT JOIN ".
			$GLOBALS['os']->table('users') . " AS u ON o.user_id=u.user_id " . $where;
		}
		else
		{
			$sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('order_info') . " AS o ". $where;
		}
		
		$filter['record_count']   = $GLOBALS['db']->getOne($sql);
		$filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;

		$left_join = '';		
		if ($filter['goods_sn'])
		{
			$left_join = " LEFT JOIN " .$GLOBALS['os']->table('order_goods'). " AS og ON og.order_id = o.order_id ";
			$where .= " AND og.goods_sn = '".$filter['goods_sn']."'";
		} 
		/* 查询 */
		$order_by_str = " $filter[sort_by] $filter[sort_order] ";
		if ($filter['module'] == 'order_list' && $filter['sort_by'] == 'delivery_time') {
			$order_by_str = " u.pay_points DESC, " . $order_by_str;
		}
		$sql = "SELECT o.order_id, o.order_sn, o.add_time,  o.invoice_no, o.order_status, o.shipping_status, o.order_amount, o.money_paid, o.pay_id, o.pay_name," .
		"o.pay_status, o.lock_status, o.consignee, o.address, o.email, o.tel, o.extension_code, o.extension_id, o.shipping_name,o.invoice_status, o.postscript,o.to_buyer, o.process_status, o.range_status, o.return_status, o.refund_status, o.question_status, o.shipping_days, o.delivery_time, " .
		"(" . order_amount_field('o.') . ") AS total_fee, " .
		"IFNULL(u.user_name, '" .'匿名客户'. "') AS buyer,tb_t.tid,tb_t.STATUS ".
		" FROM " . $GLOBALS['os']->table('order_info') . " AS o " .
		" LEFT JOIN " .$GLOBALS['os']->table('users'). " AS u ON u.user_id=o.user_id ".$left_join.
		" LEFT JOIN ".$GLOBALS['os']->table('tb_trade'). " as tb_t on tb_t.outer_order_sn=o.order_sn ".
		$where .
		" ORDER BY $order_by_str ".
		" LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ",$filter[page_size]"; 
		foreach (array('order_sn', 'consignee', 'email', 'address', 'zipcode', 'tel', 'user_name') AS $val)
		{
			$filter[$val] = stripslashes($filter[$val]);
		}
		set_filter($filter, $sql);
	}
	else
	{
		$sql    = $result['sql'];
		$filter = $result['filter'];
	}

	$row = $GLOBALS['db']->getAll($sql);
	/* 格式化数据 */
	foreach ($row AS $key => $value)
	{
		$row[$key]['formated_order_amount'] = price_format($value['order_amount']);
		$row[$key]['formated_money_paid'] = price_format($value['money_paid']);
		$row[$key]['formated_total_fee'] = price_format($value['total_fee']);
		$row[$key]['short_order_time'] = local_date('Y-m-d H:i', $value['add_time']);
		/* 计划发货时间 */
		if ($value['delivery_time'] > 1) {
			$row[$key]['short_delivery_time'] = local_date('Y-m-d H:i', $value['delivery_time']);
		} else {
			$row[$key]['short_delivery_time'] = '';
		}
		
		/* 更新订单配货状态 */
		if ($value['range_status'] == ORS_ERROR || $value['range_status'] == ORS_OUT) {
			if (!$GLOBALS['db']->getOne("SELECT id FROM " . $GLOBALS['os']->table('order_out') . " WHERE relating_order_id='" . $value['order_id'] . "'")) {
				$GLOBALS['db']->query("UPDATE " . $GLOBALS['os']->table('order_info') . " SET range_status='" . ORS_UNCONFIRMED . "' WHERE order_id='" . $value['order_id'] . "'");
			}
		}
		
		if ($value['order_status'] == OS_INVALID || $value['order_status'] == OS_CANCELED)
		{
			/* 如果该订单为无效或取消则显示删除链接 */
			$row[$key]['can_remove'] = 1;
		}
		else
		{
			$row[$key]['can_remove'] = 0;
		}
		
		if ($value['order_status'] == OS_RETURNED && $value['order_amount'] == '0.00')
		{
			$row[$key]['order_status'] = OS_REFUSED;
		}
		
		$where = "where op.log_info like '%".$value['order_sn']."'";
		$where_print = $where." and op.print_type = 1";
		$where_delivery_print .= $where." and op.print_type = 3";

		$sql = 'SELECT COUNT(*) FROM ' .$GLOBALS['os']->table('order_printlog'). ' AS op ' . $where_print;
		$count = $GLOBALS['db']->getOne($sql);
		$order_print_flag = $count >0 ?1:0;

		$sql = 'SELECT COUNT(*) FROM ' .$GLOBALS['os']->table('order_printlog'). ' AS op ' . $where_delivery_print;
		$count = $GLOBALS['db']->getOne($sql);
		$order_delivery_print_flag = $count >0 ?1:0;
		
		$row[$key]['print_flag'] = $order_print_flag;
		$row[$key]['delivery_print_flag'] = $order_delivery_print_flag;
		
		$where = '';
		$where_print = '';
		$where_delivery_print = '';
	}

	$arr = array('orders' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);

	return $arr;
}

/**
 * 获取配货缺货商品信息
 */
function out_statistic()
{
	$result = get_filter();
	$filter['module'] = 'out_statistic';
	
	/* 分页大小 */
	$filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);

	if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
	{
		$filter['page_size'] = intval($_REQUEST['page_size']);
	}
	elseif (isset($_COOKIE['OSCP']['page_size']) && intval($_COOKIE['OSCP']['page_size']) > 0)
	{
		$filter['page_size'] = intval($_COOKIE['OSCP']['page_size']);
	}
	else
	{
		$filter['page_size'] = 15;
	}
	
	/* 记录总数 */
	$sql = "SELECT COUNT(*) FROM ( SELECT goods_id, SUM(goods_number) AS total_number, color_id, size_id FROM " . $GLOBALS['os']->table('order_goods') . " WHERE order_id IN ( SELECT relating_order_id FROM " . $GLOBALS['os']->table('order_out') . " WHERE process_status IN ('" . ORS_ERROR . "','" . ORS_OUT . "') ) GROUP BY goods_id,color_id,size_id ) AS ot LEFT JOIN " . $GLOBALS['os']->table('goods_inventory') . " AS iv ON ot.goods_id=iv.goods_id AND ot.color_id=iv.color_id AND ot.size_id=iv.size_id WHERE ot.total_number>iv.goods_number_available ";
	
	$filter['record_count']   = $GLOBALS['db']->getOne($sql);
	$filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;
	
	/* 搜索缺货商品 */
	$out_goods = $GLOBALS['db']->getAll("SELECT ot.goods_id, (ot.total_number-iv.goods_number_available) AS out_number, ot.color_id, ot.size_id FROM ( SELECT goods_id, SUM(goods_number) AS total_number, color_id, size_id FROM " . $GLOBALS['os']->table('order_goods') . " WHERE order_id IN ( SELECT relating_order_id FROM " . $GLOBALS['os']->table('order_out') . " WHERE process_status IN ('" . ORS_ERROR . "','" . ORS_OUT . "') ) GROUP BY goods_id,color_id,size_id ) AS ot LEFT JOIN " . $GLOBALS['os']->table('goods_inventory') . " AS iv ON ot.goods_id=iv.goods_id AND ot.color_id=iv.color_id AND ot.size_id=iv.size_id WHERE ot.total_number>iv.goods_number_available LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ", $filter[page_size] ");
	
	/* 获取商品名称、颜色名称、尺码名称、当前可用库存 */
	foreach($out_goods as $key => $val) {
		$out_goods[$key]['goods_name'] = $GLOBALS['db']->getOne("SELECT goods_name FROM " . $GLOBALS['os']->table('goods') . " WHERE goods_id='" . $val['goods_id'] . "'");
		$out_goods[$key]['color_name'] = $GLOBALS['db']->getOne("SELECT color_name FROM " . $GLOBALS['os']->table('color') . " WHERE color_id='" . $val['color_id'] . "'");
		$out_goods[$key]['size_name'] = $GLOBALS['db']->getOne("SELECT size_name FROM " . $GLOBALS['os']->table('size') . " WHERE size_id='" . $val['size_id'] . "'");
		$out_goods[$key]['available_number'] = $GLOBALS['db']->getOne("SELECT goods_number_available FROM " . $GLOBALS['os']->table('goods_inventory') . " WHERE goods_id='" . $val['goods_id'] . "' AND color_id='" . $val['color_id'] . "' AND size_id='" . $val['size_id'] . "'");
	}
	
	$arr = array('out' => $out_goods, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);

	return $arr;
}

/**
 * 获取缺货商品关联订单信息
 */
function out_details($arr=array())
{
	$result = get_filter();
	$filter['module'] = 'out_details';
	
	foreach($arr as $key => $val) { $filter[$key] = $val; }
	
	/* 分页大小 */
	$filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);

	if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
	{
		$filter['page_size'] = intval($_REQUEST['page_size']);
	}
	elseif (isset($_COOKIE['OSCP']['page_size']) && intval($_COOKIE['OSCP']['page_size']) > 0)
	{
		$filter['page_size'] = intval($_COOKIE['OSCP']['page_size']);
	}
	else
	{
		$filter['page_size'] = 15;
	}
	
	/* 记录总数 */
	$sql = "SELECT COUNT(*) FROM ( SELECT og.order_id, SUM(og.goods_number) AS total_number, oo.id FROM " . $GLOBALS['os']->table('order_goods') . " AS og, " . $GLOBALS['os']->table('order_out') . " AS oo WHERE og.order_id=oo.relating_order_id AND og.goods_id='" . $arr['goods_id'] . "' AND og.color_id='" . $arr['color_id'] . "' AND og.size_id='" . $arr['size_id'] . "' AND oo.process_status IN ('" . ORS_ERROR . "','" . ORS_OUT . "') GROUP BY og.order_id ) AS ot ";
	
	$filter['record_count']   = $GLOBALS['db']->getOne($sql);
	$filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;
	
	/* 搜索缺货商品关联订单 */
	$out_orders = $GLOBALS['db']->getAll("SELECT * FROM ( SELECT og.order_id, SUM(og.goods_number) AS total_number, oo.id FROM " . $GLOBALS['os']->table('order_goods') . " AS og, " . $GLOBALS['os']->table('order_out') . " AS oo WHERE og.order_id=oo.relating_order_id AND og.goods_id='" . $arr['goods_id'] . "' AND og.color_id='" . $arr['color_id'] . "' AND og.size_id='" . $arr['size_id'] . "' AND oo.process_status IN ('" . ORS_ERROR . "','" . ORS_OUT . "') GROUP BY og.order_id ) AS ot LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ", $filter[page_size] ");
	
	/* 获取商品名称、颜色名称、尺码名称、当前可用库存 */
	foreach($out_orders as $key => $val) {
		$out_order = order_info($val['order_id']);
		$out_orders[$key]['order_sn'] = $out_order['order_sn'];
		$out_orders[$key]['user_name'] = $GLOBALS['db']->getOne("SELECT user_name FROM " . $GLOBALS['os']->table('users') . " WHERE user_id='" . $out_order['user_id'] . "'");
		$out_orders[$key]['shipping_days'] = $out_order['shipping_days'];
		$out_orders[$key]['order_status'] = $out_order['order_status'];
		$out_orders[$key]['available_number'] = $GLOBALS['db']->getOne("SELECT goods_number_available FROM " . $GLOBALS['os']->table('goods_inventory') . " WHERE goods_id='" . $arr['goods_id'] . "' AND color_id='" . $arr['color_id'] . "' AND size_id='" . $arr['size_id'] . "'");
	}
	
	$arr = array('out' => $out_orders, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);

	return $arr;
}

/**
 * 获得制定ID的配送站信息
 */
function get_station_name($station_id)
{
	$sql = "select s.station_name from ".$GLOBALS['os']->table('delivery_station').' as s where s.id ='.$station_id;
	$station_name = $GLOBALS['db']->getOne($sql);
	return $station_name;
}

/**
 * 更新订单对应的 pay_log
 * 如果未支付，修改支付金额；否则，生成新的支付log
 * @param   int     $order_id   订单id
 */
function update_pay_log($order_id)
{
	$order_id = intval($order_id);
	if ($order_id > 0)
	{
		$sql = "SELECT order_amount FROM " . $GLOBALS['os']->table('order_info') .
		" WHERE order_id = '$order_id'";
		$order_amount = $GLOBALS['db']->getOne($sql);
		if (!is_null($order_amount))
		{
			$sql = "SELECT log_id FROM " . $GLOBALS['os']->table('pay_log') .
			" WHERE order_id = '$order_id'" .
			" AND order_type = '" . PAY_ORDER . "'" .
			" AND is_paid = 0";
			$log_id = intval($GLOBALS['db']->getOne($sql));
			if ($log_id > 0)
			{
				/* 未付款，更新支付金额 */
				$sql = "UPDATE " . $GLOBALS['os']->table('pay_log') .
				" SET order_amount = '$order_amount' " .
				"WHERE log_id = '$log_id' LIMIT 1";
			}
			else
			{
				/* 已付款，生成新的pay_log */
				$sql = "INSERT INTO " . $GLOBALS['os']->table('pay_log') .
				" (order_id, order_amount, order_type, is_paid)" .
				"VALUES('$order_id', '$order_amount', '" . PAY_ORDER . "', 0)";
			}
			$GLOBALS['db']->query($sql);
		}
	}
}

function get_order_print_logs()
{
	$user_id  = !empty($_REQUEST['user_id']) ? intval($_REQUEST['user_id']) : 0;
	$admin_ip = !empty($_REQUEST['ip']) ? $_REQUEST['ip']         : '';

	$filter = array();
	$filter['module']       = 'order_print_logs';
	$filter['sort_by']      = empty($_REQUEST['sort_by']) ? 'op.log_id' : trim($_REQUEST['sort_by']);
	$filter['sort_order']   = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

	//查询条件
	$where = " WHERE 1 ";
	if (!empty($user_id))
	{
		$where .= " AND op.user_id = '$user_id' ";
	}
	elseif (!empty($admin_ip))
	{
		$where .= " AND op.ip_address = '$admin_ip' ";
	}

	/* 获得总记录数据 */
	$sql = 'SELECT COUNT(*) FROM ' .$GLOBALS['os']->table('order_printlog'). ' AS op ' . $where;
	$filter['record_count'] = $GLOBALS['db']->getOne($sql);

	$filter = page_and_size($filter);

	$list = array();
	$sql  = 'SELECT op.*, u.user_name FROM ' .$GLOBALS['os']->table('order_printlog'). ' AS op '.
	'LEFT JOIN ' .$GLOBALS['os']->table('admin_user'). ' AS u ON u.user_id = op.user_id '.
	$where .' ORDER by '.$filter['sort_by'].' '.$filter['sort_order'];
	$res  = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

	while ($rows = $GLOBALS['db']->fetchRow($res))
	{
		$rows['log_time'] = local_date($GLOBALS['_CFG']['time_format'], $rows['log_time']);
		$print_type = '';
		if($rows['print_type'] == 1){
			$print_type = '发货单';
		}elseif ($rows['print_type'] == 2){
			$print_type = '配货单';
		}elseif ($rows['print_type'] == 3){
			$print_type = '快递单';
		}
		$rows['print_type'] = $print_type;
		$list[] = $rows;
	}

	return array('list' => $list, 'filter' => $filter, 'page_count' =>  $filter['page_count'], 'record_count' => $filter['record_count']);
}

//文件下载
function downfile($f_name)  
{  
    if(file_exists($f_name))  
    {  
    // 输入文件标签  
    header("Cache-Control:must-revalidate,post-check=0,pre-check=0");  
    header("Content-Description:File Transfer");  
    header ("Content-type: application/octet-stream"); //定义数据类型header ("Content-Length: " . filesize ($f_name));  
    //指定内容为附件,返回路径中的文件名  
    header ("Content-Disposition: attachment; filename=" . basename($f_name));  
    readfile($f_name); // 打开文件，并输出  
    }  
    else  
    {  
    echo("文件不存在!");  
    exit;  
    }  
}

/**
 * 更新（10天内）未发货订单的承诺发货天数
 *
 * @access  public
 * @params  null
 * @return  true
 */
function auto_update_shipping_days() {
	//统计起始时间
	$statistic_time = gmtime() - 10 * 86400;
	//统计发货状态
	//$shipping_status_str = " AND shipping_status='" . SS_UNSHIPPED . "' ";
	//获得满足条件的所有订单ID
	$order_ids = $GLOBALS['db']->getCol("SELECT order_id FROM " . $GLOBALS['os']->table('order_info') . " WHERE add_time>='{$statistic_time}' $shipping_status_str ");
	foreach($order_ids as $key => $val) {
		auto_update_shipping_delivery($val);
	}
	return true;
}

/**
 * 更新单张订单，承诺发货天数、计划发货时间
 *
 * @access  public
 * @params  null
 * @return  true
 */
function auto_update_shipping_delivery($order_id=0, $order_sn='') {
	if ($order_id) {
		$order = order_info($order_id);
	} elseif ($order_sn) {
		$order = order_info(0, $order_sn);
	} else {
		return false;
	}
	/* 统计发货状态 */
	//$shipping_status_str = " AND shipping_status='" . SS_UNSHIPPED . "' ";
	/* 更新承诺发货天数 */
	if ($GLOBALS['_CFG']['use_promise_delivery'] && !$order['shipping_days']) {
		$GLOBALS['db']->query("UPDATE " . $GLOBALS['os']->table('order_info') . " SET shipping_days = ( SELECT IFNULL(MAX(g.shipping_days), 0) FROM " . $GLOBALS['os']->table('goods') . " AS g, " . $GLOBALS['os']->table('order_goods') . " AS og WHERE g.goods_id=og.goods_id AND og.order_id='" . $order['order_id'] . "' ) WHERE order_id='" . $order['order_id'] . "' $shipping_status_str ");
	}
	/* 更新计划发货时间 */
	if ($order['delivery_time'] <= 1 && 
		($GLOBALS['_CFG']['delivery_options'] == '0' ||
		($GLOBALS['_CFG']['delivery_options'] == '1' && $order['order_status'] == OS_CONFIRMED) ||
		($GLOBALS['_CFG']['delivery_options'] == '2' && $order['pay_status'] == PS_PAYED) ||
		($GLOBALS['_CFG']['delivery_options'] == '3' && $order['range_status'] == ORS_CONFIRMED))
	) {
		if ($GLOBALS['_CFG']['delivery_options'] == '0') { //下单时间
			$delivery_time = $order['add_time'] + $order['shipping_days'] * 86400;
		} elseif ($GLOBALS['_CFG']['delivery_options'] == '1') { //确认时间
			$delivery_time = $order['confirm_time'] + $order['shipping_days'] * 86400;
		} elseif ($GLOBALS['_CFG']['delivery_options'] == '2') { //支付时间
			$delivery_time = $order['pay_time'] + $order['shipping_days'] * 86400;
		} elseif ($GLOBALS['_CFG']['delivery_options'] == '3') { //配货时间
			$delivery_time = $order['range_time'] + $order['shipping_days'] * 86400;
		}
		$GLOBALS['db']->query("UPDATE " . $GLOBALS['os']->table('order_info') . " SET delivery_time='{$delivery_time}' WHERE order_id='" . $order['order_id'] . "' $shipping_status_str ");
	}
	/* 清空计划发货时间 */
	if ($order['delivery_time'] > 1 && 
		(($GLOBALS['_CFG']['delivery_options'] == '1' && $order['order_status'] == OS_UNCONFIRMED) ||
		($GLOBALS['_CFG']['delivery_options'] == '2' && $order['pay_status'] == PS_UNPAYED) ||
		($GLOBALS['_CFG']['delivery_options'] == '3' && $order['range_status'] == ORS_UNCONFIRMED))
	) {
		$delivery_time = 1;
		$GLOBALS['db']->query("UPDATE " . $GLOBALS['os']->table('order_info') . " SET delivery_time='{$delivery_time}' WHERE order_id='" . $order['order_id'] . "' $shipping_status_str ");
	}
	return true;
}

/**
 * 根据系统设置，自动配货X小时前的所有订单
 *
 * @access  public
 * @params  null
 * @return  true
 */
function auto_range() {
	if ($GLOBALS['_CFG']['auto_range'][0]) { //启用自动配货功能
		$type = 'torange_list';
		$arr = array();
		$sns = array();
		$arr['time_end'] = gmtime() - intval($GLOBALS['_CFG']['auto_range'][1]) * 3600;
		$list = order_list($type, $arr);
		$orders = $list['orders'];
		foreach($orders as $key => $val) {
			array_push($sns, $val['order_sn']);
		}
		range_orders(implode(',', $sns));
	}
	
	return true;
}

/**
 * 自动解挂满足条件的所有订单
 *
 * @access  public
 * @params  null
 * @return  true
 */
function auto_remove_lock() {
	$order_ids = $GLOBALS['db']->getCol("SELECT relating_order_id FROM " . $GLOBALS['os']->table('order_suspend') . " WHERE process_mode='0' AND process_status='0' AND end_time<'" . gmtime() . "'");
	foreach($order_ids as $key => $val) {
		$order = order_info($val);
		update_order($order['order_id'], array('process_status' => OPS_NORMAL));
		$GLOBALS['db']->query("UPDATE " . $GLOBALS['os']->table('order_suspend') . " SET process_status='1', process_mode='4', process_user='" . $_SESSION['admin_name'] . "' WHERE relating_order_id='" . $order['order_id'] . "'");
		/* 记录log */
		order_action($order['order_sn'], $order['order_status'], $order['shipping_status'], $order['pay_status'], '解挂订单-'.$order['order_sn']);
	}
	/* 清除缓存 */
   	clear_cache_files();
   	
	return true;
}

/**
 * 获取所有问题单原因
 *
 * @access  public
 * @params  null
 * @return  array
 */
function get_question_reason() {
	$reasons = array();
	$rows = $GLOBALS['db']->getAll("SELECT id, name FROM " . $GLOBALS['os']->table('return_set') . " WHERE type='3'");
	foreach($rows as $key => $val) {
		$reasons[$val['id']] = $val['name'];
	}
	
	return $reasons;
}

/**
 * 批量挂起订单的公用接口
 * 
 * @param   string / array 	$order_sn	 订单编号 / 订单编号集
 * @param 	bool			$exit		 是否出错停止
 * @param 	string			$action_note 备注
 * @return  array
 */
function suspend_orders($order_sn = '', $exit = false, $arr = array()) {
	if (!$order_sn) { return false; }
	if (strpos($order_sn, ',') > 0) { $order_sn = explode(',', $order_sn); }
	$order_sns = array();
	if (is_array($order_sn)) { $order_sns = $order_sn; }
	else { $order_sns[] = $order_sn; }
	
	/* 初始化数组 */
	$result = array();
	$result['success_sns'] = array();
	$result['error_sns'] = array();
	$result['invalid_sns'] = array();
	/* 数组赋值 */
	foreach($order_sns as $key => $val) {
		$subresult = suspend_order($val, $exit, $arr);
		if (is_array($subresult)) {
			if ($subresult['code'] == 0) { array_push($result['success_sns'], $val); }
			elseif ($subresult['code'] == 2) { array_push($result['error_sns'], $val); }
		} else {
			if ($subresult) { array_push($result['success_sns'], $val); }
			else { array_push($result['invalid_sns'], $val); }
		}
	}
	
	return $result;
}

/**
 * 单个挂起订单的公用接口
 * 
 * @param   string		 	$order_sn	 订单编号
 * @param 	bool			$exit		 是否出错停止
 * @param 	string			$action_note 备注
 * @return  array
 */
function suspend_order($order_sn = '', $exit = false, $arr = array()) {
	if (!$order_sn) { return false; }
	$result = array();
	/* 查询订单信息 */
	$order = order_info(0, $order_sn);
	$order_id = $order['order_id'];
	
	//更新订单状态为解锁
	$log_already = order_action_judge($order['order_sn'], $order['order_status'], $order['shipping_status'], $order['pay_status'], $arr['action_note']);
	if ($log_already) {
		os_header("Location: order.php?act=info&order_id=".$order['order_id']."\n");
		exit;
	} else {
		$subarr = array('process_status' => OPS_SUSPEND);
		update_order($order_id, $subarr);
		
		/* 记录挂起订单 */
		$add_time = gmtime();
		$sql = "INSERT INTO ".$GLOBALS['os']->table('order_suspend')." (relating_order_id, relating_order_sn, suspend_reason, process_user, from_user, add_time, end_time) VALUES ('".$order_id."', '".$order['order_sn']."', '".$arr['suspend_note']."','".$_SESSION['admin_name']."','挂起操作','$add_time','".$arr['suspend_end_date']."')";
		$db->query($sql);
		
		/* 记录log */
		order_action($order['order_sn'], $order['order_status'], $order['shipping_status'], $order['pay_status'], $arr['action_note']);
	}
	
	$result['code'] = 0;
	$result['message'] = '操作成功。';
	return $result;
}

/**
 * 批量解挂订单的公用接口
 * 
 * @param   string / array 	$order_sn	 订单编号 / 订单编号集
 * @param 	bool			$exit		 是否出错停止
 * @param 	string			$action_note 备注
 * @return  array
 */
function remove_suspend_orders($order_sn = '', $exit = false, $action_note = '') {
	if (!$order_sn) { return false; }
	if (strpos($order_sn, ',') > 0) { $order_sn = explode(',', $order_sn); }
	$order_sns = array();
	if (is_array($order_sn)) { $order_sns = $order_sn; }
	else { $order_sns[] = $order_sn; }
	
	/* 初始化数组 */
	$result = array();
	$result['success_sns'] = array();
	$result['error_sns'] = array();
	$result['invalid_sns'] = array();
	/* 数组赋值 */
	foreach($order_sns as $key => $val) {
		$subresult = remove_suspend_order($val, $reason_id, $exit, $action_note);
		if (is_array($subresult)) {
			if ($subresult['code'] == 0) { array_push($result['success_sns'], $val); }
			elseif ($subresult['code'] == 2) { array_push($result['error_sns'], $val); }
		} else {
			if ($subresult) { array_push($result['success_sns'], $val); }
			else { array_push($result['invalid_sns'], $val); }
		}
	}
	
	return $result;
}

/**
 * 单个解挂订单的公用接口
 * 
 * @param   string		 	$order_sn	 订单编号
 * @param 	bool			$exit		 是否出错停止
 * @param 	string			$action_note 备注
 * @return  array
 */
function remove_suspend_order($order_sn = '', $exit = false, $action_note = '') {
	if (!$order_sn) { return false; }
	$result = array();
	/* 查询订单信息 */
	$order = order_info(0,$order_sn);
	$order_id = $order['order_id'];
	
	//更新订单状态为解锁
	$log_already = order_action_judge($order_sn, $order['order_status'], $order['shipping_status'], $order['pay_status'], $action_note);
	if($log_already) {
		os_header("Location: order.php?act=suspend_list");
		exit;
	} else {
		$arr = array('process_status' => OPS_NORMAL);
		update_order($order_id, $arr);
		$sql = 'UPDATE '.$GLOBALS['os']->table('order_suspend') .' SET process_status = 1 , process_mode = 4 , process_user = "'.$_SESSION['admin_name'].'" WHERE relating_order_sn = '.$order['order_sn'];
		$GLOBALS['db']->query($sql);
		/* 记录log */
		order_action($order['order_sn'], $order['order_status'], $order['shipping_status'], $order['pay_status'], '解挂订单-'.$action_note);
	}
	
	$result['code'] = 0;
	$result['message'] = '操作成功。';
	return $result;
}

/**
 * 批量设置问题单的公用接口
 * 
 * @param   string / array 	$order_sn	 订单编号 / 订单编号集
 * @param   int     		$reason_id	 设置问题单原因
 * @param 	bool			$exit		 是否出错停止
 * @param 	string			$action_note 备注
 * @return  array
 */
function question_orders($order_sn = '', $reason_id = 0, $exit = false, $action_note = '') {
	if (!$order_sn) { return false; }
	if (strpos($order_sn, ',') > 0) { $order_sn = explode(',', $order_sn); }
	$order_sns = array();
	if (is_array($order_sn)) { $order_sns = $order_sn; }
	else { $order_sns[] = $order_sn; }
	
	/* 初始化数组 */
	$result = array();
	$result['success_sns'] = array();
	$result['error_sns'] = array();
	$result['invalid_sns'] = array();
	/* 数组赋值 */
	foreach($order_sns as $key => $val) {
		$subresult = question_order($val, $reason_id, $exit, $action_note);
		if (is_array($subresult)) {
			if ($subresult['code'] == 0) { array_push($result['success_sns'], $val); }
			elseif ($subresult['code'] == 2) { array_push($result['error_sns'], $val); }
		} else {
			if ($subresult) { array_push($result['success_sns'], $val); }
			else { array_push($result['invalid_sns'], $val); }
		}
	}
	
	$result['code'] = 0;
	$result['message'] = '操作成功。';
	return $result;
}

/**
 * 单个设置问题单的公用接口
 * 
 * @param   string			$order_sn	 订单编号
 * @param   int     		$reason_id	 设置问题单原因
 * @param 	bool			$exit		 是否出错停止
 * @param   string			$action_note 备注
 * @return  array
 */
function question_order($order_sn = '', $reason_id = 0, $exit = false, $action_note = '') {
	if (!$order_sn) { return false; }
	else { $order = order_info(0, $order_sn); }

	/* 初始化数组 */
	$result = array();
	if ($order['order_status'] == OS_FINISH || $order['order_status'] == OS_SPLITED || $order['order_status'] == OS_MERGED || 
		$order['order_stauts'] == OS_INVALID || $order['shipping_status'] == SS_SHIPPED) {
		return false;
	} else {
		if (!$reason_name = $GLOBALS['db']->getOne("SELECT name FROM " . $GLOBALS['os']->table('return_set') . " WHERE id='{$reason_id}' AND type='3'")) {
			$reason_name = '未知原因';
		}
		$arr = array('question_status' => OQS_QUESTION, 'question_time' => gmtime());
		update_order($order['order_id'], $arr);
		/* 记录挂起订单 */
		$add_time = gmtime();
		if ($GLOBALS['db']->query("INSERT INTO ".$GLOBALS['os']->table('order_question')." (relating_order_id, relating_order_sn, question_reason, process_user, from_user, add_time, question_desc) VALUES ('".$order['order_id']."', '".$order['order_sn']."', '".$reason_name."','".$_SESSION['admin_name']."','设为问题单','$add_time','$action_note')")) {
			$result['code'] = 0;
			$result['message'] = '设置订单为问题单成功。';
		} else {
			$result['code'] = 2;
			$result['message'] = '由于数据库操作错误，设置订单为问题单失败。';
			if ($exit) { sys_msg($result['message']); exit; }
		}
		/* 记录log */
		order_action($order['order_sn'], $order['order_status'], $order['shipping_status'], $order['pay_status'], $action_note, $_SESSION['admin_name'], $order['range_status'], OQS_QUESTION);
		$sn_list[] = $order['order_sn'];
	}
	
	$result['code'] = 0;
	$result['message'] = '操作成功。';
	return $result;
}

/**
 * 单个返回正常订单的公用接口
 * 
 * @param   string			$order_sn	订单编号
 * @param 	bool			$exit		是否出错停止
 * @return  array
 */
function remove_question_order($order_sn = '', $exit = false) {
	if (!$order_sn) { return false; }
	else { $order = order_info(0, $order_sn); }
	
	/* 初始化数组 */
	$result = array();
	$arr = array('question_status' => OQS_NORMAL);
	update_order($order['order_id'], $arr);
	if ($GLOBALS['db']->query("DELETE FROM " . $GLOBALS['os']->table('order_question') . " WHERE relating_order_id='" . $order['order_id'] . "'")) {
		$result['code'] = 0;
		$result['message'] = '返回正常订单成功。';
	} else {
		$result['code'] = 2;
		$result['message'] = '由于数据库操作错误，返回正常订单失败。';
		if ($exit) { sys_msg($result['message']); exit; }
	}
	/* 记录log */
	order_action($order['order_sn'], $order['order_status'], $order['shipping_status'], $order['pay_status'], $action_note, $_SESSION['admin_name'], $order['range_status'], OQS_NORMAL);
	
	$result['code'] = 0;
	$result['message'] = '操作成功。';
	return $result;
}

/**
 * 单个作废订单的公用接口
 * 
 * @param   string			$order_sn	订单编号
 * @param 	bool			$exit		是否出错停止
 * @return  array
 */
function invalid_order($order_sn = '', $exit = false) {
	if (!$order_sn) { return false; }
	else { $order = order_info(0, $order_sn); }
	
	$log_already = order_action_judge($order['order_sn'], OS_INVALID, $order['shipping_status'], $order['pay_status'], $action_note);
	if ($log_already) {
		os_header("Location: order.php?act=info&order_id=".$order['order_id']. "\n");
		exit;
	} else {
		$order_status = $order['order_status'];

		/* 库存处理 */
		manage_good_inventory($order['order_id'], 'invalid');

		/* 标记订单为“无效”、“未付款” */
		update_order($order['order_id'], array('order_status' => OS_INVALID));
		/* 记录log */
		order_action($order['order_sn'], OS_INVALID, $order['shipping_status'], $order['pay_status'], $action_note);
	}			
	
	/* 发送邮件 */
	$cfg = $_CFG['send_invalid_email'];
	if ($cfg == '1') {
		$tpl = get_mail_template('order_invalid');
		$smarty->assign('order', $order);
		$smarty->assign('shop_name', $_CFG['shop_name']);
		$smarty->assign('send_date', local_date($_CFG['date_format']));
		$smarty->assign('sent_date', local_date($_CFG['date_format']));
		$content = $smarty->fetch('str:' . $tpl['template_content']);
		if (!send_mail($order['consignee'], $order['email'], $tpl['template_subject'], $content, $tpl['is_html'])) {
			$msg = '发送邮件失败';
		}
	}

	/* 退货用户余额、积分、红包 */
	return_user_surplus_integral_bonus($order);;
	
	$result['code'] = 0;
	$result['message'] = '操作成功。';
	return $result;
}

/**
 * 退货（款）单操作公用接口
 * 
 * @param   int 	$relating_id		关联订单号 or 退货（款）单号
 * @param   string  $operation			对退货（款）单所做的操作 - save、confirm、unconfirm、pass、unpass、invalid、finish、update_goods、
 * 																update_fee
 * @param 	array	$arr				参数数组
 * @param 	bool	$exit				是否出错停止
 * @return  array	$result				
 */
function return_order($relating_id = 0, $operation = '', $arr = array(), $exit = false) {
	if (!$relating_id) { return false; }
	$action_note = isset($_REQUEST['action_note']) ? trim($_REQUEST['action_note']) : '';
	$result = array();
	/* 订单 or 退单 信息 */
	if ($operation == 'save') {
		$order = order_info($relating_id);
	} else {
		$return = order_return_info($relating_id);
	}
	/* 操作类型 */
	switch($operation) {
		case 'save':
			/* 保存退单 - 初始化 */
			$order_return['return_sn'] = get_order_return_sn();
			$order_return['relating_order_sn'] = $order['order_sn'];
			$order_return['return_order_status'] = RS_UNCONFIRMED;
			$order_return['return_order_ispass'] = 0;
			$order_return['return_reason'] = $GLOBALS['db']->getOne("SELECT id FROM " . $GLOBALS['os']->table('return_set') . " WHERE type='1' LIMIT 1");
			$order_return['return_pay'] = $GLOBALS['db']->getOne("SELECT id FROM " . $GLOBALS['os']->table('return_set') . " WHERE type='0' LIMIT 1");
			$order_return['action_user'] = $_SESSION['admin_name'];
			$order_return['add_time'] = gmtime();
			$order_return['return_consignee'] = $order['consignee'];
			$order_return['return_tel'] = '';
			$order_return['return_mobile'] = '';
			$order_return['return_email'] = '';
			$order_return['return_address'] = '';
			$order_return['return_zipcode'] = '';
			$order_return['return_goods_amount'] = '';
			$order_return['return_total_fee'] = '0.00';
			$order_return['return_type'] = 1;
			$order_return['rj'] = 0;
			$order_return['is_good_received'] = 0;
			$order_return['return_desc'] = '';
			$order_return['goods_status'] = 0;
			$order_return['payment'] = '0.00';
			$order_return['has_goods_return'] = $arr['return_goods_rec_id'] ? 1 : 0;
			/* 更新 */
			foreach($arr as $key => $val) { $order_return[$key] = $val; }
			/* 保存退单 */
			do
			{
				if ($GLOBALS['db']->autoExecute($GLOBALS['os']->table('order_return'), $order_return, 'INSERT', '', 'SILENT')) {
					break;
				} else {
					if ($GLOBALS['db']->errno() != 1062) {
						die($GLOBALS['db']->error());
					}
				}
			}
			while (true); // 防止退单号重复
			$order_return_id = $GLOBALS['db']->insert_id();
			$log_already = order_return_action_judge($order_return_id, $order_return['return_order_status'], $order_return['action_note'], $order_return['admin_user']);
			if ($log_already){
				os_header("Location: order.php?act=returned_order_info&order_return_id=".$order_return_id. "\n");
				exit;
			}else{
				/* 记录log */
				order_return_action($order_return_id, $order_return['return_order_status'], $order_return['action_note'], $order_return['admin_user']);
			}	
			/* 保存退单商品 */
			if ($arr['return_goods_rec_id']) {
				$total_fee = 0;
				$return_goods_rec_id_list = explode(',', $arr['return_goods_rec_id']);
				$return_goods_number_list = explode(',', $arr['return_goods_number']);
				$return_discount_price_list = explode(',', $arr['return_discount_price']);
				foreach ($return_goods_rec_id_list as $key => $val) {
					$goods_return_number = $return_goods_number_list[$key];
					$goods_discount_fee  = $return_discount_price_list[$key];
					$sql = "INSERT INTO " . $GLOBALS['os']->table('order_return_goods') . "(return_order_id, order_id, goods_id, goods_name, goods_sn, goods_return_number, goods_buy_number, market_price, goods_price, color_id, size_id, is_real, extension_code, parent_id, is_gift, goods_barcode) " . 
						" SELECT " . $order_return_id . ", order_id, goods_id, goods_name, goods_sn, " . $goods_return_number . ",goods_number, " . $goods_discount_fee . ",goods_price, color_id, size_id, is_real, extension_code, parent_id, is_gift, goods_barcode FROM " . $GLOBALS['os']->table('order_goods') . " WHERE rec_id = '" . $val . "'";
					$GLOBALS['db']->query($sql);
					$total_fee += $goods_discount_fee;
				}
				if (empty($arr['return_total_fee'])) {
					$GLOBALS['db']->query("UPDATE " . $GLOBALS['os']->table('order_return') . " SET return_total_fee = '" . $total_fee . "' WHERE id = '" . $order_return_id . "'");
				}
			}
			$result['return_id'] = $order_return_id;
			break;
			
		case 'confirm':
			update_order_return($return['id'], array('return_order_status' => RS_CONFIRMED));
			$log_already = order_return_action_judge($return['id'], RS_CONFIRMED, $arr['action_note'], $arr['admin_user']);
			if ($log_already) {
				os_header("Location: order.php?act=returned_order_info&order_return_id=".$return['id']. "\n");
				exit;
			} else {
				/* 记录log */
				order_return_action($return['id'], RS_CONFIRMED, $arr['action_note'], $arr['admin_user']);
			}		
			break;
		
		case 'unconfirm':
			update_order_return($return['id'], array('return_order_status' => RS_UNCONFIRMED));
			$log_already = order_return_action_judge($return['id'], RS_UNCONFIRMED, $arr['action_note'], $arr['admin_user']);
			if ($log_already) {
				os_header("Location: order.php?act=returned_order_info&order_return_id=".$return['id']. "\n");
				exit;
			} else {
				/* 记录log */
				order_return_action($return['id'], RS_UNCONFIRMED, $arr['action_note'], $arr['admin_user']);
			}
			break;
			
		case 'pass':
			update_order_return($return['id'], array('return_order_status' => RS_PASS, 'return_order_ispass' => RS_PASS));	
			$log_already = order_return_action_judge($return['id'], RS_PASS, $arr['action_note'], $arr['admin_user']);
			if ($log_already) {
				os_header("Location: order.php?act=returned_order_info&order_return_id=".$return['id']. "\n");
				exit;
			} else {
				/* 记录log */
				order_return_action($return['id'], RS_PASS, $arr['action_note'], $arr['admin_user']);
			}
			break;
			
		case 'unpass':
			update_order_return($return['id'], array('return_order_status' => RS_UNPASS, 'return_order_ispass' => RS_UNPASS));
			$log_already = order_return_action_judge($return['id'], RS_UNPASS, $arr['action_note'], $arr['admin_user']);
			if ($log_already) {
				os_header("Location: order.php?act=returned_order_info&order_return_id=".$return['id']. "\n");
				exit;
			} else {
				/* 记录log */
				order_return_action($return['id'], RS_UNPASS, $arr['action_note'], $arr['admin_user']);
			}
			break;
			
		case 'invalid':
			update_order_return($return['id'], array('return_order_status' => RS_INVALID));
			$log_already = order_return_action_judge($return['id'], RS_INVALID, $arr['action_note'], $arr['admin_user']);
			if ($log_already) {
				os_header("Location: order.php?act=returned_order_info&order_return_id=".$return['id']. "\n");
				exit;
			} else {
				/* 记录log */
				order_return_action($return['id'], RS_INVALID, $arr['action_note'], $arr['admin_user']);
			}
			break;
			
		case 'finish':
			update_order_return($return['id'], array('return_order_status' => RS_FINISHED));
			$log_already = order_return_action_judge($return['id'], RS_FINISHED, $arr['action_note'], $arr['admin_user']);
			if ($log_already) {
				os_header("Location: order.php?act=returned_order_info&order_return_id=".$return['id']."\n");
				exit;
			} else {
				/* 记录log */
				order_return_action($return['id'], RS_FINISHED, $arr['action_note'], $arr['admin_user']);
			}
	
			$order_return = order_return_info($return['id']);
			$return_status = $order_return['return_order_ispass'];
	
			if($return_status == RS_PASS) {
				/* todo 处理退款 */
				$refund_note = '';
				$refund_type = $order_return['return_pay'];
				$refund_amount = $order_return['return_total_fee'];
				order_refund($order_return, $refund_type, $refund_note, $refund_amount);				
	
				/* 如果订单用户不为空，计算积分，并退回 */
				if ($order_return['user_id'] > 0) {
					$user = user_info($order_return['user_id']);
					/* 计算并退回积分 */
					$integral = integral_to_give($order_return);
					log_account_change($order_return['user_id'], 0, 0, (-1) * intval($integral['rank_points']), (-1) * intval($integral['custom_points']), sprintf('由于退货或未发货操作，退回订单 %s 赠送的积分', $order_return['order_sn']));
	
					/* 计算并退回红包 */
					//return_order_bonus($order_return['order_id']);
				}
	
				/* 如果使用库存 */
				if ($_CFG['use_storage'] == '1') {
					$sql = "SELECT o.goods_return_number,o.goods_id,o.color_id,o.size_id FROM " . $GLOBALS['os']->table('order_return_goods') . " AS o WHERE o.return_order_id = '" . $return['id'] . "' AND is_real = 1";
					$res = $GLOBALS['db']->getAll($sql);
					foreach ($res as $res_goods) {
						$res_goods_id = $res_goods['goods_id'];
						$res_color_id = $res_goods['color_id'];
						$res_size_id  = $res_goods['size_id'];
						$goods_return_number = $res_goods['goods_return_number'];
						change_good_inventory($res_goods_id, $res_color_id, $res_size_id, $goods_return_number, false);
						change_good_inventory($res_goods_id, $res_color_id, $res_size_id, $goods_return_number, false, 1);
					}
				}
			}
	
			/* 退回用户余额、积分、红包 */
			//return_user_surplus_integral_bonus($order_return);
	
			/* 清除缓存 */
			clear_cache_files();
			break;
			
		case 'update_goods':
			if ($arr['return_goods_rec_id']) {
				$return_goods_rec_id_list = explode(',', $arr['return_goods_rec_id']);
				$return_goods_number_list = explode(',', $arr['return_goods_number']);
				$GLOBALS['db']->query("DELETE FROM " . $GLOBALS['os']->table('order_return_goods') . " WHERE return_order_id='" . $return['id'] . "'");
				foreach ($return_goods_rec_id_list as $key => $val) {
					$goods_return_number = $return_goods_number_list[$key];
					$sql = "INSERT INTO " . $GLOBALS['os']->table('order_return_goods') . "(return_order_id, order_id, goods_id, goods_name, goods_sn, goods_return_number, goods_buy_number, market_price, goods_price, color_id, size_id, is_real, extension_code, parent_id, is_gift, goods_barcode) " . 
						" SELECT " . $return['id'] . ", order_id, goods_id, goods_name, goods_sn, " . $goods_return_number . ",goods_number, " . $goods_discount_fee . ",goods_price, color_id, size_id, is_real, extension_code, parent_id, is_gift, goods_barcode FROM " . $GLOBALS['os']->table('order_goods') . " WHERE rec_id = '" . $val . "'";
					$GLOBALS['db']->query($sql);
				}
				if (empty($arr['return_total_fee'])) {
					$GLOBALS['db']->query("UPDATE " . $GLOBALS['os']->table('order_return') . " SET return_total_fee = '" . $arr['return_total_fee'] . "' WHERE id = '" . $return['id'] . "'");
				}
			}
			break;
			
		case 'update_fee':
			$GLOBALS['db']->query("UPDATE " . $GLOBALS['os']->table('order_return') . " SET return_total_fee='" . $arr['return_total_fee'] . "' WHERE id='" . $return['id'] . "'");
			break;
			
		default :
			break;
	}
	$result['code'] = 0;
	$result['message'] = '操作成功。';
	return $result;
}

/**
 * 判断订单差额的公用接口
 * 
 * @param   string 	$role_list			角色级别（超级管理员等）
 * @param   int  	$admin_id			当前管理员ID
 * @param 	float	$difference			订单差额数值
 * @return  bool	true / false				
 */
function difference_order($role_list = '', $admin_id = 0, $difference = 0) {
	if (!$role_list) { $role_list = $_SESSION['role_list']; }
	if (!$admin_id) { $admin_id = $_SESSION['admin_id']; }
	if ($role_list == '超级管理员') { return false; }
	$role_difference = $GLOBALS['db']->getOne("SELECT ar.role_difference FROM " . $GLOBALS['os']->table('acl_role') . " AS ar, " . $GLOBALS['os']->table('acl_role_user') . " AS aru WHERE ar.role_id=aru.role_id AND aru.user_id='{$admin_id}'");
	if (abs($difference) <= abs($role_difference)) { return false; }
	return true;
}

?>
